Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date problem

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

like image 299
user345602 Avatar asked Dec 17 '22 23:12

user345602


1 Answers

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.

like image 140
Pete Avatar answered Jan 01 '23 16:01

Pete