new \DateTime() gives the same value for multiple requests - php

I have used the following piece of code in some APIs to limit the request
sleep(1);
// date_value_from_db is taken from DB, question time as example
$date_value_from_db = '2022-12-31 11:18:00Z';
$lastCreatedAt = new DateTime($date_value_from_db);
$now = new \DateTime();
#echo $now->format('Y-m-d H:i:s');
$timeElapsedInSecs = $now->getTimestamp() - $lastCreatedAt->getTimestamp();
// Only execute if the time difference is more than 60 secs
if ($timeElapsedInSecs < 60) {
// throw Exception
}
// Proceed further
If you call this API in a loop, $now->format('Y-m-d H:i:s') returns the same value 3-4 times in a row, after that, it shows the correct current time. and so on. For example echo $now->format('Y-m-d H:i:s') in the above code looks like this:
2022-12-30 11:30:25
2022-12-30 11:30:25
2022-12-30 11:30:25
2022-12-30 11:31:32
2022-12-30 11:31:32
...
Also, the $timeElapsedInSecs value is also the same
Ideally, $now should give the current time for each call. But it's not happening.
Do you guys see any issues with the above code?

I created a file name testdt.php on my local system like this:
<?php
$now = new \DateTime();
echo $now->format('Y-m-d H:i:s')."\n";
When executing this script 100 time (I am on Windows) using:
for /L %f in (1,1,100) do #curl "http://localhost/test/testdt.php"
I do see the returned value change.
When you need more change, you should change 'Y-m-d H:i:s' to 'Y-m-d H:i:s.v', this will add milli-seconds

Related

PHP Datetime Remove Time

How do I remove time from a date in PHP, for example:
20170803173418 I want to take 4 minutes and 13 seconds away and get the new datestamp that would be 20170803173005
What code do I use to get this?
EDIT
I currently have:
$dbTime = $row['aptDeadline']; // This is the appointment end time stored in DB
$dbTime = new DateTime($dbTime);
$currentTime = date("YmdHis"); // This is the current time
$currentTime = new DateTime($currentTime);
$counterTime = $row['aptDeadline']; //This is the time a countdown clock works from inDB
$counterTime = new DateTime($counterTime);
$difference = $currentTime->diff(new DateTime($dbTime)); // Calculate the time between now and the apt time in the db
I now need some code that if the $difference is positive, can take this figure away from the $counterTime stamp
You can use the modify method of the DateTime class in PHP:
<?php
$time = new \DateTime('20170803173418');
$time->modify('-4 minutes')->modify('-13 seconds');
echo $time->format('YmdHis');
This will print the result you want.

diff() and date_diff() in PHP not working for some reason

I’m having a problem using PHP’s ‘diff()’ or ‘date_diff()’ between two dates of mine. Basically when I run anything that attempts to compare dates or try to define something as a date the page will stop loading at that point.
<?php
// My starting point is the $dirty_date variable.
// It is collected from a string, parsed,
// and ends up being an integer-based date / seconds past Unix Epoch
//I am also including some echos along the way for debugging purposes.
echo "Check 1: ".$dirty_date."<br>";
$systemdate = date("U");
echo "Check 2: ".$systemdate."<br>";
//$interval = $dirty_date->diff($systemdate);
echo "check 3: ".$interval;
Here are the results:
Check 1: 1490781836
Check 2: 1490806703
check 3:
Check 3 returned nothing because I have the line which diffs it commented out. I have it commented out because if it is enabled, the page doesn't load anything else past that point.
First, $newdate is not defined. Second, $dirty_date must be a DateTime object currently it is just an integer. I will assume you want to compare $dirty_date and $systemdate
Try this:
$dirty_date_obj = new DateTime();
$dirty_date_obj->setTimestamp((int) $dirty_date);
$system_date_obj = new DateTime();
$system_date_obj->setTimestamp((int) $systemdate);
echo "interval between dirty and system: ".$dirty_date_obj->diff($system_date_obj)->format('%a Days and %h hours');
Also please type this in the beginning of your code to see the error messages so it isn't just a blank page if some error happens:
error_reporting(E_ALL); ini_set('display_errors', '1');
Here's an example
$dirty_date = new \DateTime();
$dirty_date->setTimestamp("your integer date");
echo "Check 1: ".$dirty_date->format(\DateTime::ISO8601)."<br>";
$systemdate = new \DateTime();
echo "Check 2: ".$systemdate->format(\DateTime::ISO8601)."<br>";
$interval = $dirty_date->diff($systemdate);
echo "check 3: ".$interval->format("%R%a days");
link to DateInterval ($interval var) formats http://php.net/manual/en/dateinterval.format.php

strtotime every refresh minutes and seconds change why

$order_startdate = date('Y-m-d H:i:s'); // current date & time
$NewDate=Date('Y-m-d H:i:s', strtotime("+3 days", strtotime($order_startdate))); // 3 days increase Date And Time also
var_dump($NewDate);
I am get string(19) 2015-06-29 06:56:42
after refresh it has changed 2015-06-29 07:03:19
I want the time do not changed time i want
$NewDate I'm Used in NextPayment Date in Subscription Payment
For Now
i am in struggle !
Thanks
You are creating a new Date() instance every time the script loads, which means that every time you refresh the page new time value is returned because of the nature of time (it changes over time :D)
If you want to save the time, that means, you need to write the value of your variable when it is created into database/somewhere else.
Following from #Slim Kallari's answer, you could do this, to get a new date only when one is not already set:
if(!isset($_SESSION['NewDate']))
{
$NewDate=Date('Y-m-d H:i:s', strtotime("+3 days", strtotime($order_startdate)));
$_SESSION['NewDate'] = $NewDate;
}
else
{
$NewDate= $_SESSION['NewDate'];
}
var_dump($NewDate);
That way, you create a new Date instance if one doesn't already exists. Make sure to add session_start(); before creating your session variable, though.
Finally I research myself and implemented as working solution finally here it is best instead of dom just remove dom and try it should did a trick
$date = $order->order_date;// checkout placeorder date
$trial = '1';
$subsc = date('Y-m-d H:i:s', strtotime($date. '+ '. $trial . 'days'));

timezone and time() issue, time now is less than time before

I am using wordpress where the defualt timezone is UTC, though I do not understand why this would make a difference because it is the same person that wants to update something on the website, and the time compared is for that person, in this case me.
So, I want to update my password, and when that happens a new datetime value is inserted in the appropriate table, and when I click the link in the email link that I receive, the page I go to makes a new time like so:
$time_now = date('Y-m-d H:i:s');
$time_now = strtotime($time_now);
And before that I pull the appropriate value from the table and convert it to time like so:
$time_then = strtotime($time_then);
So even though it is ME doing all this from the same computer, I get a result where $time_then is BIGGER than $time_now.
The time seems to be off for like 2 hours, so I can add 2 hours to $time_now, but would that work the way it should for all people, regardless of their country?
And why is $time_then bigger than $time_now anyway?
UPDATE:
Just to make it clear, the time I insert into the DB is CORRECT, while the time I get with php on the page is wrong ( 1 hour less in my case ).
UPDATE 2: code
foreach ($q as $key => $value) {
$time_then = $value->req_date;
$e = $value->email;
}
echo 'Time then normal: '.$time_then.'<br>';
$time_then = strtotime($time_then);
// check how much time has elapsed
$time_now = date('Y-m-d H:i:s');
echo 'Time now normal: '.$time_now.'<br>';
$time_now = strtotime($time_now);
echo 'Time then: '.$time_then.'<br>';
// echo 'Time now: '.$time_now.'<br>';
$time_now = time();
echo 'Time now: '.$time_now.'<br>';
if ($time_now > $time_then) {
echo 'Good <br>';
} else {
echo 'Abnormal <br>';
}
So after I go to the link provided in the email ( after the req_date has been inserted into the DB ), I get for example the following shown on the page:
Time then normal: 2014-11-07 11:11:23
Time now normal: 2014-11-07 10:11:38
Time then: 1415358683
Time now: 1415355098
Abnormal
So after I go to the link provided in the email ( after the req_date has been inserted into the DB ), I get for example the following shown on the page:
$time_now = date('Y/m/d H:i:s');
$time_now = strtotime($time_now);

PHP MYSQL compare time with created in database

I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}

Categories