Determine time difference between now and stored date and time - php

in my sql table I save the date and time of a certain action, how can I print it via php on the contrary, or how long ago did it take place?
for example
|date |
|05-28-2020 17:12:05 |
and at 17:30:05 it will be written on my php page
"18 minutes ago"

Load the date from the database using a mysqli_query and store the result in $original_date.
Create a date object from the string in the database.
$old_date = new DateTime($original_date);
Get the current date in the same format and store it in another variable.
$current_date = new DateTime(date("m-d-Y H:m:s"));
Get the difference between the two dates.
$difference = $old_date->diff($current_date);
Convert the difference to minutes and display message.
echo($difference->m . "minutes ago");
Here is the full code for you to use:
# Get database value and store in $original_date
$old_date = new DateTime($original_date);
$current_date = new DateTime(date("m-d-Y H:m:s"));
$difference = $old_date->diff($current_date);
echo($difference->m . "minutes ago");

Related

Having a hard time understanding how to manipulate date and time in PHP

I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php

DateTime current date + 2 mins compared to stored datetime

I'm trying to compare these 2 DateTimes.
I'm storing one in a database that is stored whenever a new row is inserted.
The other one is the current DateTime, but I'm trying to add two minutes to it and then compare it.
My current code:
$time = $cached_data["last_update"];
$date = new DateTime ('now');
$datef = $date->format('Y-m-d H:i:s');
// Check if the cached data has expired and if it has then update the data
if($datef > ($time)) {
echo "updated";
}
Echoing both the $datef and the $time gives:
$datef: 2016-04-06 00:23:43
$time: 2016-04-05 18:21:03
and the script echoes out "updated".
I realize the time on my system and the time of my database are different, but how would I add the two minutes to the $datefand would this work?

How to compare current time with old time in PHP

I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
DateDiff: http://www.php.net/manual/en/datetime.diff.php
DateInterval: http://www.php.net/manual/en/class.dateinterval.php
Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
if ($diff/60/60 <= 1){
//do your thing here
{
First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
Then convert the difference to days as follows :
$days=$difftime/24*60*60;
Once you get the days you can get the minutes from it as below to compare to meet your need.
$timediff = $days * 24 * 60;

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
}

Figuring out the difference in days between events

I have a MySQL DB with StartDates in the format of yyyy-mm-dd and starttimes in the format of HH:MM using a 24 hour clock. What would be the easiest way to compare the difference of two days in PHP? Would using a datetime object could I set it to be with the information given and just give it to zeros for the seconds? I need to get the amount of time between both dates down to the minute. I was putting the startdate (Just the day since its always within the same month for my application) and time together concatenated together and then pulling out what I need like below, but I haven't been able to get it straight yet. Thanks for the look!
$tempvar1 = $times[$i][$j];
$tempvar2 = $times[$i][$j+1];
$day1 = $tempvar1[0].$tempvar1[1];
$day2 = $tempvar2[0].$tempvar2[1];
$hours1 = $tempvar1[2].$tempvar1[3];
$hours2 = $tempvar2[2].$tempvar2[3];
$minutes1 = $tempvar1[5].$tempvar1[6];
$minutes2 = $tempvar2[5].$tempvar2[6];
$numdays = ($day2-$day1) - 1;
$time1 = ($hours1*60)+$minutes1;
$time2 = ($hours2*60)+$minutes2;
MySQL has plenty of date/time functions:
SELECT TIMEDIFF(endtime, starttime), DATEDIFF(endtime, starttime)
FROM ...
doc links for timediff and datediff
That'll you get strings in the format of 'hh:mm:ss.ssss' for timediff, and a straight-up integer representing the days between the two dates, respectively.

Categories