Samuel Hapak
Samuel Hapak

Reputation: 7182

PHP calculating time difference, result 1 hour wrong

I want to calculate difference of two times and print it in pretty way. I know the difference will never exceed 24 hours, so I tried the following

$time = 7200; //time difference in seconds
date("H:i:s", $time); // should print 02:00

The result is unexpected, it prints 03:00 instead.

What am I doing wrong?

Upvotes: 2

Views: 1927

Answers (3)

Samuel Hapak
Samuel Hapak

Reputation: 7182

You should never use date to compute time difference. Firstly it is ugly hack. It was not intended for that purpose. And secondly, it works reliably only when timezone set to UTC.

Now, why it does not work: PHP function date takes two arguments, format and timestamp, the latter is defined as number of seconds from 1st January 1970 00:00 UTC called unix epoch. So if you call date("H:i", 3600) and your timezone is set to UTC, it will return "01:00", cause it represents time one hour after unix epoch and the epoch was at the midnight.

The problem is, unix epoch was at the midnight only in UTC, not in the other timezones. And this is the source of the incorrect result.

Upvotes: 1

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

The PHP date() function is meant for formatting absolute time stamps (as in "Friday, 20 July 2012, 15:02 UTC"), not for time differences (as in "3 hours and 5 minutes ago").

In some cases, it is possible to trick date() into producing something that looks like a correctly formatted time difference by setting your time zone to UTC and relying on the fact that the Unix epoch happens to fall on midnight in UTC. However, even then, this will only work for positive time differences of less than 24 hours.

Instead, the correct solution is to use a function designed for formatting time differences, or write one yourself. Here's a simple function to do so:

function format_time_difference ( $delta ) {
    $sign = ( $delta < 0 ? "-" : "" );
    $delta = abs( $delta );
    return sprintf( "%s%02d:%02d:%02d", $sign, $delta / 3600,
                    ($delta / 60) % 60, $delta % 60 ); 
}

Of course, you can extend this function to e.g. include days in the output if you like.

Upvotes: 1

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 1108

Why not the DateTime::diff??

Here, check PHP.net for DateTime class

Grabbed from php.net datetime diff page:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

//Outputs +2 days

Upvotes: 2

Related Questions