display hours and minutes after calculating difference between 2 unix times php - php

i have been having trouble displaying the hours and minutes after calculating the difference between 2 different unix timestamps. Lets say i have these 2 unix timestamps:
1) 1384327800
2) 1384300800
the difference is
27000
if i divide 27000/3600 i get
7.5
but what i want is to display
7:30
or
7 hours and 30 minutes
what is the best way to go about this?

All you need to do it a little calculation:
$diff = 27000;
$hour = floor($diff / 3600);
$min = floor(($diff - $hour * 3600) / 60);
$sec = $diff - $hour * 3600 - $min * 60;
echo "$hour hours, $min minutes, $sec seconds";
Or try it with DateTime class:
$dt1 = new DateTime('#1384327800');
$dt2 = new DateTime('#1384300801');
$diff = $dt1->diff($dt2);
echo $diff->format('%h hours, %i minutes, %s seconds');

Algorithmic way (with no automatic calculation with any function/library) :
$diff_in_minutes = ($timestamp1 - $timestamp2) / 60;
$minutes = $diff_in_minutes % 60;
$hours = ($diff_in_minutes - $minutes) / 60;
$diff_string = $hours . ':' . $minutes;

Look at DateTime() and DateInterval::format()
$dt1 = new DateTime('#1384327800');
$dt2 = new DateTime('#1384300800');
$diff = $dt1->diff($dt2);
echo $diff->format('%h hours and %i minutes');
This last little bit will remove unnecessary time periods from your string if so desired.
$elapsed = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', ' 1 hours, ', ' 1 minutes'), array('1 year, ', '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), $elapsed);
echo $elapsed;

For full long formatting exactly as described:
date_default_timezone_set('UTC');
$timestamp1 = new DateTime('#1384327800');
$timestamp2 = new DateTime('#1384300800');
$diff = $timestamp1->diff($timestamp2);
$timemap = array('y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second');
$timefmt = array();
foreach ($timemap as $prop => $desc) {
if ($diff->$prop > 0) {
$timefmt[] = ($diff->$prop > 1) ? "{$diff->$prop} {$desc}s" : "{$diff->$prop} $desc";
}
}
$diffstr = (count($timefmt) > 1)
? $diff->format(sprintf('%s and %s',
implode(', ', array_slice($timefmt, 0, -1)), end($timefmt)))
: end($timefmt);
var_dump($diffstr);
This gave me the following:
string(22) "7 hours and 30 minutes"

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!

PHP: Output seconds in H:M value

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

User friendly date formatting [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 9 years ago.
I am trying to display user friendly date formatting such as "1 hour and 15 minutes", "4 days and 8 hours" to the user. However my script is displaying 0 hours as 23 for some reason.
$date = '2014-01-15 15:00' # PAST DATE
$now = Date("Y-m-d H:m:s");
$seconds = strtotime($now) - strtotime($date);
$days = floor($seconds / 86400);
$hours = floor(($seconds - ($days * 86400)) / 3600);
$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));
if($days > 0)
{
if($days == 1)
{
return $days . ' dag ' . $hours . ' timmar';
} else {
return $days . ' dagar ' . $hours . ' timmar';
}
}
if(($hours < 24) AND ($hours > 0))
{
return $hours . ' timmar';
}
if($minutes < 60)
{
return $minutes . ' minuter';
}
Can anyone see what is causing this? Am I doing it the correct way? Note that $date is user supplied in the past.
There are much easier ways to do this:
$past = new DateTime('2014-01-15 15:00');
$now = new DateTime();
$interval = $now->diff($past);
echo $interval->format('%y years, %m months, %d days,
%h hours, %i minutes, %S seconds');
An obvious improvement is to use now show periods of time that have zero values (i.e. 0 days):
$elapsed = $interval->format('%y years, %m months, %d days,
%h hours, %i minutes');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,',
' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ',
' 1 hours, ', ' 1 minutes'), array('1 year, ',
'1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'),
$elapsed);
Use something like this:
$date = '2014-01-15 15:00' # PAST DATE
now = Date("Y-m-d H:m:s");
$t = strtotime($now) - strtotime($date);
$time = date('g:iA M dS', $t );
$diff = time() - $t;
if ( $diff < 60 )
{
return "a few seconds ago";
}
elseif ( $diff < 3600 )
{
return "about ".( int ) ($diff/60) ." mins ago";
}
elseif ( $diff < 86400 )
{
if ( ( int ) ($diff/3600) == 1 )
{
return "about an hour ago";
}
else
{
return "about ".( int ) ($diff/3600) ." hours ago";
}
}
else if( $diff < 172800 )
{
return "about a day ago";
}
elseif ( $diff > 172800 )
{
return "$time";
}

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