views:

458

answers:

3

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 = 'Thu 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>';
+1  A: 

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

Pascal MARTIN
A: 

Make your life easier & just use strtotime():

$timestamp = strtotime('Thu Mar 11 2010 13:00:00 GMT-0500 (EST)');
Pickle
I don't believe this will maintain the timezone information, which may or may not be what the OP needs (depending on what he wants to do with the DateTime object afterward).
Justin Johnson
strtotime not TZ aware: $timestamp = strtotime('Thu Mar 11 2010 13:00:00 GMT-0500 (EST)'); echo '<pre>$timestamp: '; echo $timestamp; echo '</pre>'; $timestamp = strtotime('Thu Mar 11 2010 13:00:00 GMT-0500 (PST)'); echo '<pre>$timestamp: '; echo $timestamp; echo '</pre>';
Andrew Warner
A: 

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 */
Andrew Warner
And the date_default_timezone_set should always be set anyway in config/init or php.ini, so you wouldn't normally need date_default_timezone_set right there in the code
Andrew Warner
I'm on php 5.3 which throws exception on new DateTime($s) (no second arg) if date_default_timezone_set not set
Andrew Warner