Markus Finell
Markus Finell

Reputation: 336

time difference showing one hour too much

I am trying to calculate the time difference between two timestamps. After looking around here for a while I found this solution:

$start = strtotime(10:00:00);
$end = strtotime(10:30:00);
$diff = ($end - $start);

echo 'Time 1: '.date('H:i:s', $start).'<br>';
echo 'Time 2: '.date('H:i:s', $end).'<br>';
echo 'Diff: '.date('H:i:s', $diff);

It seems to work, the time 1 and time 2 show the correct times, but the difference shows 01:30:00, not 00:30:00 as it should. I have tried setting the correct timezone but it didnt help. Any ideas?

Upvotes: 1

Views: 1442

Answers (2)

Glavić
Glavić

Reputation: 43552

When you need to format seconds to HH:MM:SS don't use date() function, since it formats timestamp based on current timezone. If you would use gmadate() for formating time, your problem will be solved:

echo 'Diff: ' . gmdate('H:i:s', $diff);

Convert seconds to HH:MM:SS format: https://stackoverflow.com/a/20870843/67332

Upvotes: 1

softvar
softvar

Reputation: 18435

Refer Dates diff in PHP

$date1 = "2013-08-11";
$date2 = "2012-07-12";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Or

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

//or simply
//echo "difference " . $interval->days . " days ";

Note

It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier.

Upvotes: 1

Related Questions