开发者

Parsing javascript date string to timestamp. the tz info is in the date!

I have to parse a javascript date string to a timestamp. If the date string has the TZ info, why do I have to supply a TZ object in the DateTime constructor and again with setTimezone()? Is there an easier way to do this that is aware of the TZ info in the date?

$s = 'Th开发者_开发知识库u Mar 11 2010 13:00:00 GMT-0500 (EST)';
$dt_obj = new DateTime($s, new DateTimeZone('America/New_York')); /* why? the TZ info is in the date string */

// again
$dt_obj->setTimezone(new DateTimeZone('UTC'));

echo 'timestamp  ' , $dt_obj->getTimestamp(), '<br>';


Do you really have to put it there ?

Can you just not use this :

$s = 'Thu Mar 11 2010 13:00:00 GMT-0500 (EST)';
$dt_obj = new DateTime($s);

Note : the second parameter to DateTime::__construct is optionnal : its default value is null


And, later, you can do :

var_dump($dt_obj->getTimestamp());
var_dump($dt_obj->getTimezone()->getName());

And you'll get :

int 1268330400
string '-05:00' (length=6)

If EST is Eastern Time Zone, I suppose it's OK, as it's UTC-5 ?


As a sidenote : I'm in France, which is at UTC+1 ; so it doesn't seem that my local timezone has any influence


Make your life easier & just use strtotime():

$timestamp = strtotime('Thu Mar 11 2010 13:00:00 GMT-0500 (EST)');


Okay, here's the deal. It is aware of TZ in the date string. Just set the default timezone to anything using date_default_timezone_set (). Doesn't matter what -- it just has to be set.

//date_default_timezone_set('America/New_York');
date_default_timezone_set('UTC');

$s = 'Thu Mar 11 2010 13:00:00 GMT-0500 (EST)';
$dt_obj = new DateTime($s);
echo 'timestamp  ' , $dt_obj->getTimestamp(), '<br>';
/* 1268330400 */

$s = 'Thu Mar 11 2010 13:00:00 GMT-0800 (PST)';
$dt_obj = new DateTime($s);
echo 'timestamp  ' , $dt_obj->getTimestamp(), '<br>';   
/* 1268341200 <- different, good */

A lot easier than:

$s = 'Thu Mar 11 2010 13:00:00 GMT-0500 (EST)';
$dt_obj = new DateTime($s, new DateTimeZone('America/New_York')); 
$dt_obj->setTimezone(new DateTimeZone('UTC'));
echo 'timestamp  ' , $dt_obj->getTimestamp();
/* 1268330400 */
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜