Kevin Bradshaw
Kevin Bradshaw

Reputation: 6417

strtotime date weird result

Given the following string date: Fri Sep 02 2011 21:00:00 GMT+0100 (GMT Daylight Time)

in php if I do a strtotime on the above, and then convert it back to a string date, it seems to gain an hour.

echo $str_date,"  Vs ",date("c",strtotime($str_date));

Produces:

Fri Sep 02 2011 21:00:00 GMT+0100 (GMT Daylight Time) Vs 2011-09-02T22:00:00+01:00

I realise this is to do with daylight savings, but how does one compensate for this?

Upvotes: 5

Views: 977

Answers (4)

salathe
salathe

Reputation: 51950

I realise this is to do with daylight savings, but how does one compensate for this?

By not using date() and strtotime(); the DateTime class is preferred.

$str_date = 'Fri Sep 02 2011 21:00:00 GMT+0100';
$datetime = new DateTime($str_date);
echo $datetime->format('c'); // 2011-09-02T21:00:00+01:00

or in procedural style

$str_date = 'Fri Sep 02 2011 21:00:00 GMT+0100';
echo date_format(date_create($str_date), 'c'); // 2011-09-02T21:00:00+01:00

Aside: if you wish to still use date()/strtotime() then, as the other answers and your own observations show, you need to be careful with the time zones in use in the date string and your script.

Upvotes: 1

s.webbandit
s.webbandit

Reputation: 17000

Seems like strtotime() renders your time as SOAP format: YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection?

result is:

"2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"

You can try to format your time string as some other time format. Look in http://www.php.net/manual/en/datetime.formats.compound.php

Upvotes: 0

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

Which PHP version do you use? What is your date.timezone setting? I'm asking because I cannot reproduce your output running PHP 5.3.6 on Mac OS X:

$str_date   = 'Fri Sep 02 2011 21:00:00 GMT+0100  (GMT Daylight Time)';
echo $str_date,"  Vs ",date("c",strtotime($str_date));
// Fri Sep 02 2011 21:00:00 GMT+0100  (GMT Daylight Time)  Vs 1970-01-01T01:00:00+01:00

This is correct because Fri Sep 02 2011 21:00:00 GMT+0100 (GMT Daylight Time) is not a valid date/time string.

$str_date   = 'Fri Sep 02 2011 21:00:00 GMT+0100';
echo $str_date,"  Vs ",date("c",strtotime($str_date));
// Fri Sep 02 2011 21:00:00 GMT+0100  Vs 2011-09-02T22:00:00+02:00

This is correct because I'm in GMT+2.

Upvotes: 1

ajreal
ajreal

Reputation: 47311

I think you misunderstanding,
there is not day light saving in this case,
BUT GMT, you gain one hour because of that

in my timezone (GMT+8)

php -r "echo date('r', strtotime('Fri Sep 02 2011 21:00:00 GMT+0100'));"
Sat, 03 Sep 2011 04:00:00 +0800

which I gain 7 hours, due to GMT+8 - GMT+1 = 7

Upvotes: 3

Related Questions