views:

67

answers:

4
+3  Q: 

PHP date problem

Hi, I have web service in PHP which gets dateTime object (from asp) . I want to parse this date in my custom format . The date originally is in format "2010-07-05T00:00:00+02:00" . When I'm trying this:

$oDate = strtotime($date_from_webservice);
$sDate = date("d.m.Y",$oDate);
echo $sDate;

I'm getting date "07.04.2010" which is one day earlier. Why?

Thanks

+2  A: 

Because your timezone offset is less than +2 hours. Let's say you're in Lisbon, where the current timezone offset is UTC + 1 hours. Then that time will be "2010-07-04T23:00:00+01:00", which is one day before.

You can use DateTime instead:

$date = new DateTime("2010-07-05T00:00:00+02:00");
echo $date->format("d.m.Y"); //echoes 05.07.2010

This automatically associates the timezone "+02:00" to the date, ensuring that the formatting is correct.

On the other hand:

$date = new DateTime("2010-07-05T00:00:00+02:00");
$date->setTimeZone(new DateTimezone("Europe/Lisbon"));
echo $date->format("d.m.Y"); //echoes 04.07.2010
Artefacto
Any idea how to resolve this ?
+6  A: 

Looking at it, the original date ($date_from_webservice) is in the timezone GMT+2, and the time is midnight.

I'm guessing the timezone PHP is configured for is different (prob. UTC), so the date "appears" to be the day before. However, the conversion is perfectly correct.

To resolve this you have a couple of options:

  1. Ask/tell the origin server to return the datetime as UTC (which is what it should be doing really), make sure PHP is using UTC as well.

  2. Configure PHP to the same timezone as the source server, using date_default_timezone_set or in the php.ini. Note you can't just add/subtract hours, due to daylight savings.

  3. If you're sure the datetime format is consistent, use substr. Eg:

    $sDate=substr($oDate, 8, 2).'.'.substr($oDate, 5, 2).'.'.substr($oDate, 0 ,4);

Option 1 is the best. Option 2 is risky if the origin server has it's timezone changed. Option 3 assumes the datetime format will never change.

Pete
Why should the origin server return the datetime as UTC? You think the timezone is generally irrelevant?
Artefacto
If you're serving datetimes as a web service, it's best to serve as UTC for pretty obvious reasons, in the example the origin server should be outputting `2010-07-04T22:00:00+00:00`. I never said the timezone was irrelevant...
Pete
+1  A: 

PHP uses a (evil) global timezone when formatting date strings. You can use $oDate's timezone by calling date_default_timezone_set:

$oDate = strtotime($date_from_webservice);

$oldTimezone = date_default_timezone_get();
date_default_timezone_set(date('e', $oDate));

$sDate = date('d.m.Y', $oDate);

date_default_timezone_set($oldTimezone);

echo $sDate;
strager
A: 

Thanks to all, i have resolved the problem with your help. Now it works :)