views:

288

answers:

4

Hi there,

I've got kind of a tricky question, I already searched every related question on Stackoverflow and neither solved my conundrum, although I think I'm running in circles, so here's the question:

I've got this code:

$val = (strtotime('2010-03-22 10:05:00')-strtotime('2010-03-22 09:00:00'))

This returns correctly $val = 3900 (3600 seconds = 1 hour, 300 seconds = 5 mins)

But doing this:

echo date("H:i",$val)."<br>";

returns 02:05

even doing this:

echo date("H:i",3900)."<br>";

returns 02:05 (just to be naively sure)

Doing this:

echo date("H:i eTO",3900)."<br>";

returns

02:05 System/LocaltimeCET+0100

Which is correct, my timezone is CET and is +1.

What's going on? Is date() correcting the timezone for some reason? Or am I doing anything wrong?

+2  A: 

Hi,

This is happening because using date(, ) returns epoch (00:00:00 01 January 1970 UTC) + the number of seconds in the timestamp. It will localise itself to your timezone, so if you provided it with a timestamp of 0 it would return 01:00:00 01 January 1970 UTC+1.

Sean
Answered my own but you arrived 1 second earlier :D
Lex
Thanks ;) Glad to see you worked it out though! Self-learning is handy! :)
Sean
A: 

I did this:

date_default_timezone_set('Europe/Helsinki');

Which is GMT+02:00

and the result was:

03:05 Europe/HelsinkiEET+0200

So, it IS actually correcting for timezone, the explanation now I found to be pretty simple (I had an epiphany): date() counts seconds FROM "1 Jan 1970 GMT" so actually 3900 in my timezone and example is correctly "02:05" from that date...

Self learning +1 -_-'

Lex
+2  A: 

Yes, it is correcting the timezone. When you do

$val = (strtotime('2010-03-22 10:05:00')-strtotime('2010-03-22 09:00:00'))

, what's stored in $val is a timestamp for 01:05, 1 Jan 1970 UTC. See Wikipedia's article on Unix Time.

If you're working with the difference between two timestamps, I'd suggest using DateTime::diff (requires PHP 5.3).

nemetroid
I would have used DateTime::diff but I can't update PHP version, stuck with 5.2.something, but no problem though, I figured it out :D and thanks for answer.
Lex
A: 

This is actually the right behavior, because date works with local time, and you are on GMT +1. You give it a timestamp (3900) which is 1/1/1970 1:05 and it just ads 1 to get it to your timezone.

If this is your intended use, than you can just subtract the GMT offset of your machine to get the right value.

Dinu Florin