Calculate difference between 2 times in hours in PHP - php

I have two times -
For eg- the current time - 08:24 and date is 02/01/2013 in dd/mm/yyyy format
and I have another time at 13:46 and date is 31/12/2012 . So, how can I calculate the difference between the 2 times in hours using PHP. (i.e. 42.63 hours)
Thanks in advance.

Convert them both to timestamp values, and then subtract to get the difference in seconds.
$ts1 = strtotime(str_replace('/', '-', '02/01/2013 08:24'));
$ts2 = strtotime(str_replace('/', '-', '31/12/2012 13:46'));
$diff = abs($ts1 - $ts2) / 3600;

Another way is to use PHP's date-related classes. The example below uses DateTime::diff() to get a DateInterval object ($interval). It then uses the interval's properties to arrive at the total number of hours in the interval.
$a = DateTime::createFromFormat('H:i d/m/Y', '08:24 02/01/2013');
$b = DateTime::createFromFormat('H:i d/m/Y', '13:46 31/12/2012');
$interval = $a->diff($b);
$hours = ($interval->days * 24) + $interval->h
+ ($interval->i / 60) + ($interval->s / 3600);
var_dump($hours); // float(42.633333333333)

I got a simple solution, Try this one -
echo getTimeDiff("10:30","11:10");
function getTimeDiff($dtime,$atime)
{
$nextDay = $dtime>$atime?1:0;
$dep = explode(':',$dtime);
$arr = explode(':',$atime);
$diff = abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
$hours = floor($diff/(60*60));
$mins = floor(($diff-($hours*60*60))/(60));
$secs = floor(($diff-(($hours*60*60)+($mins*60))));
if(strlen($hours)<2){$hours="0".$hours;}
if(strlen($mins)<2){$mins="0".$mins;}
if(strlen($secs)<2){$secs="0".$secs;}
return $hours.':'.$mins.':'.$secs;
}

If you have the dates as timestamps (use strtotime if needed), then just subtract them, optionally take the absolute value, then divide to 3600 (number of seconds in an hour). Easy ^_^

I think the following code is useful to get an idea about how to calculate time difference using PHP
function date_diff($date_1 , $date_2 , $format) {
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$diff = date_diff($datetime1, $datetime2);
return $diff->format($format);
}
The above function is useful to calculate difference between two times as well as dates. The dates are given as arguments with the output format.
The output format are given below:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds' => 1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day' => 1 Year 3 Month 14 Days
// '%m Month %d Day' => 3 Month 14 Day
// '%d Day %h Hours' => 14 Day 11 Hours
// '%d Day' => 14 Days
// '%h Hours %i Minute %s Seconds' => 11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds' => 49 Minute 36 Seconds
// '%h Hours => 11 Hours
// '%a Days

Just putting this here, for anyone who needs to find the difference between two dates/timestamps in Hours, Minutes 'AND' Seconds!!
$futureDate_raw = '12/13/2018'; // This is your finish date.
$fdate = strtotime($futureDate_raw);
$hours = (($fdate - time()) / 3600;
$mins = (($fdate - time()) % 3600) / 60;
$seconds = ((($fdate- time()) % 3600) % 60);

I found this is simplest way to find time difference, it always works for me
$timestamp1 = strtotime(date('Y-m-d H:i'));
$timestamp2 = strtotime("2020-04-05 18:00");
$diff = abs($timestamp2 - $timestamp1)/(60*60);
echo $diff;

Following code is useful to get time difference with format H:I:S:
Method 1 :
function time_diff($startDateTime, $endDateTime) {
$startDateTime = strtotime(str_replace('/', '-', $startDateTime));
$endDateTime = strtotime(str_replace('/', '-', $endDateTime));
$difference = abs($startDateTime - $endDateTime);
$hours = floor($difference / 3600);
$minutes = floor(($difference % 3600) / 60);
$seconds = $difference % 60;
return str_pad($hours, 2, '0', STR_PAD_LEFT). ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT). ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT);
}
Method 2 :
function time_diff($startDateTime, $endDateTime) {
$datetime1 = new DateTime($startDateTime);
$datetime2 = new DateTime($endDateTime);
$interval = $datetime1->diff($datetime2);
return $interval->format('%H:%I:%S');
}
Thank You!

Related

format diff php (%h+%i)/60 [duplicate]

I have two times -
For eg- the current time - 08:24 and date is 02/01/2013 in dd/mm/yyyy format
and I have another time at 13:46 and date is 31/12/2012 . So, how can I calculate the difference between the 2 times in hours using PHP. (i.e. 42.63 hours)
Thanks in advance.
Convert them both to timestamp values, and then subtract to get the difference in seconds.
$ts1 = strtotime(str_replace('/', '-', '02/01/2013 08:24'));
$ts2 = strtotime(str_replace('/', '-', '31/12/2012 13:46'));
$diff = abs($ts1 - $ts2) / 3600;
Another way is to use PHP's date-related classes. The example below uses DateTime::diff() to get a DateInterval object ($interval). It then uses the interval's properties to arrive at the total number of hours in the interval.
$a = DateTime::createFromFormat('H:i d/m/Y', '08:24 02/01/2013');
$b = DateTime::createFromFormat('H:i d/m/Y', '13:46 31/12/2012');
$interval = $a->diff($b);
$hours = ($interval->days * 24) + $interval->h
+ ($interval->i / 60) + ($interval->s / 3600);
var_dump($hours); // float(42.633333333333)
I got a simple solution, Try this one -
echo getTimeDiff("10:30","11:10");
function getTimeDiff($dtime,$atime)
{
$nextDay = $dtime>$atime?1:0;
$dep = explode(':',$dtime);
$arr = explode(':',$atime);
$diff = abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
$hours = floor($diff/(60*60));
$mins = floor(($diff-($hours*60*60))/(60));
$secs = floor(($diff-(($hours*60*60)+($mins*60))));
if(strlen($hours)<2){$hours="0".$hours;}
if(strlen($mins)<2){$mins="0".$mins;}
if(strlen($secs)<2){$secs="0".$secs;}
return $hours.':'.$mins.':'.$secs;
}
If you have the dates as timestamps (use strtotime if needed), then just subtract them, optionally take the absolute value, then divide to 3600 (number of seconds in an hour). Easy ^_^
I think the following code is useful to get an idea about how to calculate time difference using PHP
function date_diff($date_1 , $date_2 , $format) {
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$diff = date_diff($datetime1, $datetime2);
return $diff->format($format);
}
The above function is useful to calculate difference between two times as well as dates. The dates are given as arguments with the output format.
The output format are given below:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds' => 1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day' => 1 Year 3 Month 14 Days
// '%m Month %d Day' => 3 Month 14 Day
// '%d Day %h Hours' => 14 Day 11 Hours
// '%d Day' => 14 Days
// '%h Hours %i Minute %s Seconds' => 11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds' => 49 Minute 36 Seconds
// '%h Hours => 11 Hours
// '%a Days
Just putting this here, for anyone who needs to find the difference between two dates/timestamps in Hours, Minutes 'AND' Seconds!!
$futureDate_raw = '12/13/2018'; // This is your finish date.
$fdate = strtotime($futureDate_raw);
$hours = (($fdate - time()) / 3600;
$mins = (($fdate - time()) % 3600) / 60;
$seconds = ((($fdate- time()) % 3600) % 60);
I found this is simplest way to find time difference, it always works for me
$timestamp1 = strtotime(date('Y-m-d H:i'));
$timestamp2 = strtotime("2020-04-05 18:00");
$diff = abs($timestamp2 - $timestamp1)/(60*60);
echo $diff;
Following code is useful to get time difference with format H:I:S:
Method 1 :
function time_diff($startDateTime, $endDateTime) {
$startDateTime = strtotime(str_replace('/', '-', $startDateTime));
$endDateTime = strtotime(str_replace('/', '-', $endDateTime));
$difference = abs($startDateTime - $endDateTime);
$hours = floor($difference / 3600);
$minutes = floor(($difference % 3600) / 60);
$seconds = $difference % 60;
return str_pad($hours, 2, '0', STR_PAD_LEFT). ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT). ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT);
}
Method 2 :
function time_diff($startDateTime, $endDateTime) {
$datetime1 = new DateTime($startDateTime);
$datetime2 = new DateTime($endDateTime);
$interval = $datetime1->diff($datetime2);
return $interval->format('%H:%I:%S');
}
Thank You!

time to month week and day convertion

I have issue when converting date to a left weeks, hours and months.
Here my code:
$time_elapsed = time() - $createDate;
$hours = round($time_elapsed / 3600);
$days = round($time_elapsed / 86400 );
$weeks = round($time_elapsed / 604800);
$months = round($time_elapsed / 2600640 );
But when i display for example $months, i get: 565
$createDate =1470165198; // Created with time(); 15 minutes ago
Supposed to show 0 no ? since there around 15 minutes difference between them.
$create_date must be an integer not string
thus
$createDate = 1470165198; // no quotes
If you make use of the PHP DateTime class it can be very easily done like this
$start = new DateTime('2015-08-01 00:00:00'); // instead of your time()
$end = new DateTime('2016-09-02 01:01:01');
$interval = $start->diff($end);
echo $interval->format('%y year %m Months %d Days %i Minutes %s Seconds');
RESULT:
+1 year +1 Month +1 Day +1 Minute +1 Second
Now if your required output is different you can play with the formatting as much as you like.
To initialize your a DateTime object using your $createDate = time() timestamp you can do :-
$start = new DateTime();
$start->setTimestamp($createDate);
$end = new DateTime('now');
$interval = $start->diff($end);
echo $interval->format('%y year %m Months %d Days %i Minutes %s Seconds');
The PHP DateTime Manual

Given number of hours get number of months, days, hours, and minutes PHP

I know there might be different ways using timestamps and stuff but I'm having trouble converting number of hours into something that human would understand. I do not have power to change anything in the database.
There is a column that holds number of hours, so it can be something like 134.37 hours. Now I can not display that and tell user that something will happen in 134.37 hours I need to convert it into months, days, hours, minutes, seconds.
For example:
Given Hours: 23.33
Desired Result: 0 Months, 0 Days, 23 Hours, 19 Minutes, 48 seconds (dont care about seconds)
Now I need months and days since number of hours might be large. The code I started with does give me number of hours, minutes and seconds but i cant get days and months.
$months = $days = $hour = $min = $sec = 0;
$decimalHours = 23.33;
//convert to hours
$hour = (int)$decimalHours;
$decimalHours -= $hour;
//convert to minutes and subtract minutes
$decimalHours *= 60;
$min = (int)$decimalHours;
$decimalHours -= $min;
$decimalHours = number_format($decimalHours, 10);
//convert to seconds
$decimalHours *= 60;
$sec = (int)$decimalHours;
echo $hour . ' hours, ' . $min . ' minutes, ' . $sec . ' seconds';
Please help if you know a function that does it or an easier way.
You can achieve this with DateTime extension:
$hours = 23.33;
$zero = new DateTime('#0');
$offset = new DateTime('#' . $hours * 3600);
$diff = $zero->diff($offset);
echo $diff->format('%m Months, %d Days, %h Hours, %i Minutes');
demo
Code new DateTime('#0'); creates DateTime object with timestamp 0, which is January 1 1970 00:00:00 GMT. Timestamp 0 is zero number of seconds since the Unix Epoch.In this example it basically doesn't matter how you create DateTime object, I just wanted it to be in UTC offset and to ignore DST. You can also create DateTime object like new DateTime('UTC'); (which is current datetime in UTC timezone) or something familar.
Edit:
I guess I can ignore months and display days + hours + minutes is better than just hours
In that case just use echo $diff->format('%a Days, %h Hours, %i Minutes');. See the difference where I replaced format of days from %d to %a. Read the DateInterval::format() what this characters mean. You can also access parameters directly on DateInterval objects as echo $diff->days; echo $diff->h; // etc. (use print_r($diff); to see those parameters).
How long is a month? 30 days? 31 days? 30.5 days? 365.24 / 12 ?
Skipping that, you can do:
$hours = 23.33;
$days = floor($hours / 24);
$remaining_hours = $hours - $days * 24;
$hours = floor($remaining_hours);
$minutes = round(($remaining_hours - $hours) * 60);
echo $days . " days " . $hours . " hours " . $minutes . " minutes";
// 0 days 23 hours 20 minutes
First off the hours thing is bonkers. I'm assuming they are always adjusted to be current (ie 10 hours to something happening... 9 hours.. 8 hours)
But have you tried a simple php strtotime() approach? Format your output to a date/time/countdown using timestamp?
$dateFromToday = strtotime('+23.33 hours'); // get unixtimestamp from today + hours
echo date('l jS \of F Y h:i:s A', $dateFromToday); // format my date output
Maybe I am oversimplifying it tho.
If you populate the $datetime variable (sorry for unconventional variable names), the following code applies.
This:
$original = 23.33;
$hours = floor($original);
$minutes = floor(60 * ($original - $hours));
echo sprintf('Total: %s hours, %s minutes', $hours, $minutes);
echo '<br />';
$datetime = new \DateTime('-2 hours 15 minutes');
$destined = new \DateTime(sprintf('+ %s hours %s minutes', $hours, $minutes));
echo sprintf('Scheduled Time: %s', $destined->format('Y-m-d sH:i:s'));
echo '<br />';
$interval = $destined->diff($datetime);
echo sprintf('Time Remaining: %s months, %s days, %s hours, %s minutes',
$interval->m, $interval->d, $interval->h, $interval->i);
Outputs:
Total: 23 hours, 19 minutes
Scheduled Time: 2014-01-04 1915:15:19
Time Remaining: 0 months, 1 days, 1 hours, 4 minutes

Is there something built into PHP to convert seconds to days, hours, mins?

For example if I have:
$seconds = 3744000; // i want to output: 43 days, 8 hours, 0 minutes
Do I have to create a function to convert this? Or does PHP already have something built in to do this like date()?
function secondsToWords($seconds)
{
$ret = "";
/*** get the days ***/
$days = intval(intval($seconds) / (3600*24));
if($days> 0)
{
$ret .= "$days days ";
}
/*** get the hours ***/
$hours = (intval($seconds) / 3600) % 24;
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = (intval($seconds) / 60) % 60;
if($minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = intval($seconds) % 60;
if ($seconds > 0) {
$ret .= "$seconds seconds";
}
return $ret;
}
print secondsToWords(3744000);
This is very simple and easy to find days , hours, minute and second in core php :
$dbDate = strtotime("".$yourdbtime."");
$endDate = time();
$diff = $endDate - $dbDate;
$days = floor($diff/86400);
$hours = floor(($diff-$days*86400)/(60 * 60));
$min = floor(($diff-($days*86400+$hours*3600))/60);
$second = $diff - ($days*86400+$hours*3600+$min*60);
if($days > 0) echo $days." Days ago";
elseif($hours > 0) echo $hours." Hours ago";
elseif($min > 0) echo $min." Minutes ago";
else echo "Just now";
An easy way to accomplish this nowadays is using DateTimeImmutable, DateInterval and PHP 5.5.0 or higher:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$now = new DateTimeImmutable('now', new DateTimeZone('utc'));
$difference = $now->diff($now->add($interval))->format('%a days, %h hours, %i minutes');
The result will be:
43 days, 8 hours, 0 minutes
The code adds the seconds to a date and calculates the difference to it. Like this, the seconds are transformed into the specified days, hours and minutes.
Warning 1: Working without UTC - Clock changes
You may not specify the DateTimeZone in the constructor of the DateTimeImmutable object to UTC.
$now = new DateTimeImmutable();
There are regions in this world, where the clock changes on specific days of the year. Most countries in the EU change between a summer- and winter-time for example.
If your date interval overlaps the day on that a clock change occurs and your server is set to the related region for that clock change, the result might change as well. This is best shown with the following example:
$twentyFourHours = new DateInterval('PT24H');
$twentyFiveHours = new DateInterval('PT25H');
//Pacific time changed from summer- to winter-time on that day
$summerToWinter = new DateTimeImmutable('2018-11-04');
If you add 24 hours to the $summerToWinter date, you will get the following result:
$extra24Hours = $summerToWinter->add($twentyFourHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra24Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra24Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-04 23:00
0 days, 24 hours, 0 minutes
As you can see, between 00:00 and 23:00 on that day lay 24 hours, which is technically correct. Because of the clock change the timelap between 02:00 and 03:00 occured twice on that day.
Adding 25 hours will result in this:
$extra25Hours = $summerToWinter->add($twentyFiveHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra25Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra25Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-05 00:00
1 days, 0 hours, 0 minutes
As we can see, 1 day elapsed, that has had 25 hours. If this is applied for the 3744000 seconds from the original question, the result would show:
43 days, 7 hours, 0 minutes
The information, that an elapsed day has had 25 hours, is not shown though.
Also, I was not able to recreate the same effect for a day that changes the clock from winter to summer time, that should only elapse 23 hours.
Warning 2: Working with the raw DateInterval object
Using this code without DateTimeImmutable will cause the wrong output:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$difference = $interval->format('%a days, %h hours, %i minutes, %s seconds');
Now, only the seconds are set in the DateInterval object. $difference would be:
(unknown) days, 0 hours, 0 minutes, 3744000 seconds
I like Ian Gregory's answer the most and upvoted it but thought i'd just simplify it a little bit :
function secondsToWords($seconds)
{
$days = intval(intval($seconds) / (3600*24));
$hours = (intval($seconds) / 3600) % 24;
$minutes = (intval($seconds) / 60) % 60;
$seconds = intval($seconds) % 60;
$days = $days ? $days . ' days' : '';
$hours = $hours ? $hours . ' hours' : '';
$minutes = $minutes ? $minutes . ' minutes' : '';
$seconds = $seconds ? $seconds . ' seconds' : '';
return $days . $hours . $minutes . $seconds;
}

Get duration between date time formats

how to get duration between start_date and end_date in hrs min sec format in php?
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
Use DateTime class:
$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');
$dd = date_diff($end_date, $start_date);
To get hours use $dd->h, minutes - $dd->i, seconds - $dd->s.
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
I would
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);
EDIT
I made an error in assuming that the time difference would be less then a day, so if the time difference is greater then a day, you will only see the Hours:minuetes:seconds, which is probably not what you want (if it is ignore this)
So I would now
$seconds = $difference % 60; //seconds
$difference = floor($difference / 60);
$min = $difference % 60; // min
$difference = floor($difference / 60);
$hours = $difference; //hours
echo "$hours : $min : $seconds";
Sorry for the correction
This function will help you
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
/*
$interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)
*/
http://php.net/manual/en/function.date-diff.php
format those string to date
transform those date to milliseconds
do endate - stardate
from the result calculate the h:mm:ss
See it working here: http://codepad.viper-7.com/FPuOks
$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15

Categories