Get difference between 2 date_time in minutes - php

Im trying to get the difference between 2 differente dates in minutes, but is not outputting correctly.
Ex:
$then = "2017-01-23 18:21:24";
//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();
//Calculate the difference.
$difference = $now - $then;
//Convert seconds into minutes.
$minutes = floor($difference / 60);
echo $minutes;
Is outputting 611 minutes, and is wrong since from "2017-01-23 18:21:24" to "2017-01-24 12:36:24" it past much more than 611 minutes. Is my code incorrect?

Try to set your default timezone
date_default_timezone_set('Europe/Copenhagen');
Ofc change Europe/Copenhagen for the one that suits your needs.

If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php

I've checked your code it works perfectly So if have any doubt see your result
But you got wrong, so to ignore this set your timezone.

Related

PHP - Difference between two times

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...
20180808180653
And this is a finisher time...
20180808180654
The difference between them is roughly 1 hour 24, but when i use...
date('h:i:s', $finshTime-$startTime)
I get 03:24:20 not 01:34:20.
Can someone please help?
The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).
$start = '20180808180653';
$end = '20180808180654';
$diff = $end - $start;
var_dump($diff); //1
$d = date('h:i:s', $$diff);
var_dump($d); //04:00:01
//the above is wrong. You need to try something like the code below
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));
I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.
Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.
First check if the type of $finshTime and $startTime are integer.
you can use get variable type:
gettype($startTime);
if this is the case try this with ():
$diff_date = date('h:i:s', ($finshTime - $startTime) );
if $startTime and $finshTime are string try this:
$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Check if time elapsed since date is more than X days

I need to create a PHP script that pulls the timestamps of various stuff from a database (logs, messages, logins, etc) and removes them if they are older than X amount of days. I am poor at doing work with time and am a bit stumped on the best way to do this.
I realize I could separate the day/month/year in the string using explode() and compare these with a bunch of If statements, but would like to use a more efficient method. Something like the following would be the correct way to do this correct?
$dt = "2011-03-19 10:05:44";
//if $dt is older than 90 days
if((time()-(60*24*90)) > strtotime($dt))
{
}
Subtract (minutes*hours*days) from time() or are the numbers wrong?
You can use DateTime class for this. Example:
$dt = "2011-03-19 10:05:44";
$date = new DateTime($dt);
$now = new DateTime();
$diff = $now->diff($date);
if($diff->days > 90) {
echo 'its greater than 90 days';
}

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;

Subtract php format date and set the difference value in a textbox [duplicate]

How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.

Determining elapsed time

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;

Categories