PHP: Output seconds in H:M value - php

I have the following code:
echo $diff . ' / ';
echo gmdate("H:i:s", $diff);
This produces
129600 / 12:00:00
However 129600 is 36 hours and not 12, so how could I amend the code to be total hours (36) rather than being 1 day and 12 hours as I don't need to show the day
So if it was 36 hours and 1 minute, I'd want to show: 36:01 or 36:1
Thanks

$hours = floor($diff/ 3600);
$minutes = floor(($diff/ 60) % 60);
$seconds = $diff% 60;
$diff= $hours . ":" . $minutes . ":" . $seconds ;
echo $diff ;
Try this. This may give you the desired result.

Fetch the days, multiply it by 24 - then add the hours to that, and append the minutes and seconds.
Note that if you have more than 30/31 days, this will stop working again and you will need to account for months or possibly years as well.
$days = gmdate("d", $diff);
$hours = gmdate("H", $diff);
echo ($days*24 + $hours).gmdate(":i:s", $diff);
You can instead go the other way around - extract the seconds and minutes!
$seconds = str_pad($diff % 60, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($diff/60 % 60, 2, '0', STR_PAD_LEFT);
$hours = str_pad($diff/3600, 2, '0', STR_PAD_LEFT);
echo "$hours:$minutes:$seconds";
Live demo at https://3v4l.org/Aa8E6

As of your comment : This doesn't work if it's 08-05-2019 12:00 AM and 09-05-2019 12:00 PM - it brings back 60.
Try following code
$sstartdate = new DateTime('08-05-2019 12:00:00 AM');
$edatetime = new DateTime('09-05-2019 12:00:00 PM');
$since_start = $sstartdate->diff($edatetime);
$hours = ($since_start->days * 24)+($since_start->h);
$min = $since_start->i;
$sec = $since_start->s;
echo $hours.':'.$min;
Output: 36:00
36 hours and 00 minute

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!

Calculate Number of hours worked in 2 24 hour time format PHP

Hi I have a two variable in 24 hour time format and want to compute the number of hours worked. But I get negative and wrong value
I'm using PHP and here's my code
$endtime = date( 'g:i A', strtotime( $itInfo['endTime'] ) );
$startTime = date( 'g:i A', strtotime( $itInfo['startTime'] ) );
$timeDiff = (strtotime($endtime) - strtotime($startTime))/60/60;
$total = strtotime($endtime) - strtotime($startTime);
$hours = floor($total / 60 / 60);
$minutes = round(($total - ($hours * 60 * 60)) / 60);
echo "FROM ".$itInfo['startTime']." TO ".$itInfo['endTime']." (".$hours.'.'.$minutes."hours)";`
Here's the output FROM 22:00 TO 03:00 (-19.0hours) which is wrong the output should be 5 Hours.
Try this:
$timeDiff = strtotime($itInfo['endTime']) - strtotime($itInfo['startTime']);
echo substr('00'.($timeDiff / 3600 % 24),-2)
.':'. substr('00'.($timeDiff / 60 % 60),-2)
.':'. substr('00'.($timeDiff % 60),-2);
As others have stated, best to work with timestamps. But with your current code, you should be able to add this right before the echo:
if ($itInfo['startTime'] > $itInfo['endTime']) {
$hours = 24 - $hours;
}
This would be: 24 - 19 = 5.
Also, be sure to take add abs() in your $total variable as well:
$total = abs(strtotime($endtime) - strtotime($startTime));

Difference between 2 datetimes in minutes?

I got the following code:
$now = new DateTime();
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
which returns the difference between 2 datetimes in minutes. If then is 2015-05-31 19:15:31 and now is 2015-05-31 19:20:31 it returns 5 minutes. But as soon as the day changes, if then changes to 2015-05-30 19:15:31 it still returns 5 minutes when it should be 1445 minutes. Could someone point out my error?
Because months, years can have an arbitrary number of minutes, you might best want to convert your dates to timestamps (seconds since epoch) so you only have to divide by 60. Fortunately, it's easy to do so:
$now = new DateTime('2015-05-31 19:20:31');
$then = new DateTime('2015-05-30 19:15:31');
$seconds = abs($now->format('U') - $then->format('U'));
$minutes = floor($seconds / 60);
print $minutes;
That is because it's a full day. So you have to calculate how many minutes one day is. So this should work for you:
Basically here I just get all days, hours, minutes and seconds from the interval and multiply them by the multiplier to get minutes out of them.
<?php
//Test data
$now = "2015-05-30 19:20:31";
$accountExists['sub_limit'] = "2015-05-30 19:15:31";
$now = new DateTime($now);
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$multiplier = ["days" => 60*24, "h" => 60, "i" => 1, "s" => 1/60];
$minutes = 0;
$values = array_intersect_key((array)$interval, $multiplier);
foreach($values as $k => $v)
$minutes += $v*$multiplier[$k];
echo "Diff. in minutes is: " . $minutes;
?>
output:
Diff. in minutes is: 1445

Calculate difference between 2 times in hours in 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!

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;
}

Categories