Reputation: 598
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
Upvotes: 4
Views: 3479
Reputation: 1773
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:
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.
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.
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.
Upvotes: 7
Reputation: 97805
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
Upvotes: 3
Reputation: 90012
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;
Upvotes: 1