开发者

Another datetime to GMT conversion question

开发者 https://www.devze.com 2023-03-14 09:17 出处:网络
I am pulling a feed from Google Calendar.It has the event start time in this format: StartDate: 2011-06-25T18:00:00.000-05:00

I am pulling a feed from Google Calendar. It has the event start time in this format:

StartDate: 2011-06-25T18:00:00.000-05:00

I understand that the -05:00 is the timezone offset. I need the above to get put into the mySQL database in GMT time. I was just reading about date() and gmdate() but I'm afraid I'm pretty new at this and I don't seem to be getting the results I need.

Right now the above code ends up being this in my datetime colum in mySQL:

2011-06-25 18:00:00

I need the above to be:

2011-06-25 23:00:00

But I need a dynamic way to do this so any user with a different timezone will get the correct results-IE: I need the f开发者_如何学Gounction to be smart enough to read the timezone offset and make the needed changes regardless of the offset. I'm hoping there is a PHP function that does this already?

Thanks for any help!


If you use strtotime, you can do this:

<?
date_default_timezone_set('UTC');
$date = strtotime('2011-06-25T18:00:00.000-05:00');
echo date('Y-m-d H:i:s',$date);

This results on my system in:

2011-06-25 23:00:00


Something like this will, probably, work:

// get date with time zone
$date = new DateTime('2011-06-25T18:00:00.000-05:00');

// get time zone offset in minutes
$offset = $date->getOffset();

// get date without offset
$date2 = new DateTime($date->format('Y-m-d\TH:i:s'));

// apply offset to get UTC time
$date2->add(new DateInterval('PT' . $offset . 'M'));

probably it's a little complicated, but I'm not a "PHP guy", so..


The easiest way would be to use DateTime and DateTimeZone - this is also PHP 5.2.x compatible.

$date = new DateTime('2011-06-25T18:00:00.000-05:00');
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:s');

This solution does not require you to change the configured PHP timezone with date.timezone or date_default_timezone_set().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号