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
Related
I have this basic PHP time calculation which just substracts between two timestamps but it's giving back an additional hour.
echo date('h:i:s',strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00'));
I am expecting the answer to be 55 min ( 00:55:00 )
Instead it gives 01:55:00
EDIT: On PHP fiddle it works fine, on my server it doesn't (and the time is set properly)
Any insight?
create date object by date_create() function
$date1 = date_create("y-m-d H:i:s");
$date2 = date_create("y-m-d H:i:s");
print_r(date_diff($date1-$date2));
you can get the diff of year, month , hour , min, sec
Try this. See comments for explanation and output.
<?php
$from = '2020-11-15 11:05:00';
$to = '2020-11-15 12:00:00';
// 'U' gets UNIX seconds since epoch.
$fromSeconds = (new DateTime($from))->format('U');
$toSeconds = (new DateTime($to))->format('U');
$interval = $toSeconds - $fromSeconds;
// Get number of days
$days = floor($interval / 86400);
$interval -= $days * 86400;
// Get number of hours
$hours = floor($interval / 3600);
$interval -= $hours * 3600;
// Get number of minutes
$minutes = floor($interval / 60);
$interval -= $hours * 60;
var_dump($days); // 0
var_dump($hours); // 0
var_dump($minutes); // 55
This explains what happened in your first attempt:
$seconds = strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00');
var_dump($seconds); // 3300
// You're passing an _interval_ to date(), where it expects a timestamp
// in UNIX epoch format.
// Which means, seconds counted from UNIX time 0.
// UNIX time 0 starts at 1970-01-01 01:00:00!
// See:
echo date('Y-m-d H:i:s', 0); // 1970-01-01 01:00:00!
// Your code is formatting the TIME, not the INTERVAL of your argument.
// Which is the 1 from 01:00:00 and 55 minutes from your value.
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!
I have two Timestamps
2016-01-01 00:00:00
2016-01-02 23:59:59
Using PHP how can I calculate the number of hours and minutes between the two times and get the result as a decimal with 2 places after the .
currently I have this:
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = date_diff($Start,$Finish);
$Hours = $Interval->format('%h.%i');
But the result is incorrect if the user starts the timer on Day 1 and finishes on day 2.
You could multiply the number of days by 24 to convert them to hours, then sum the hours and concatenate the minutes:
$start = new DateTime('2016-01-01 00:00:00');
$end = new DateTime('2016-01-02 23:59:59');
$interval = $end->diff($start);
$days = $interval->format('%d');
$hours = 24 * $days + $interval->format('%h');
echo $hours.':'.$interval->format('%i');
You could format the DateTime as a UNIX timestamp, and then simply subtract to get the total seconds, and format the output with gmdate().
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = $Start->format('U') - $Finish->format('U');
$Hours = gmdate("H:i:s", $Interval);
Try this.
$Hours = $Interval->format('%a.%h.%i');
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!
I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
You can use DateTime class also -
$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);
/**
* #var \DateInterval $diff
*/
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise
\DateInterval documentation.
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
You can try this :
$time1 = new DateTime('06:56:58');
$time2 = new DateTime('15:35:00');
$time_diff = $time1->diff($time2);
echo $time_diff->h.' hours';
echo $time_diff->i.' minutes';
echo $time_diff->s.' seconds';
Output:
8 hours 38 minutes 2 seconds
The problem is that using these values the result is 167 and it should be 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to
$date2 = "2014-03-14 05:49:23";
You can try this:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
php.net - strtotime()