简体   繁体   中英

convert any date string to timestamp without timezone

I'm getting xml and rss feeds and putting the data into a database. I've run into two different date formats so far...

Wed, 21 Jul 2010 00:28:50 GMT

And

2010-07-20T17:33:19Z

I'm sure there will be more. My postgresql database for the date is timestamp without time zone. Is there an existing function in php or is there a procedure to convert the any date strings to timestamp without time zone (Ymd H:i:s)?

Use date with strtotime :

$date = date('Y-m-d H:i:s', strtotime('Wed, 21 Jul 2010 00:28:50 GMT'));
echo $date;

Result:

2010-07-21 05:28:50

.

$date = date('Y-m-d H:i:s', strtotime('2010-07-20T17:33:19Z'));
echo $date;

Result:

2010-07-20 22:33:19

You don't need to convert it at all. PostgreSQL should convert automatically:

postgres=# create table test_tz (f1 timestamp without time zone);
CREATE TABLE
postgres=# insert into test_tz (f1) values ('Wed, 21 Jul 2010 00:28:50 GMT');
INSERT 0 1
postgres=# insert into test_tz (f1) values ('2010-07-20T17:33:19Z');
INSERT 0 1
postgres=# select f1 from test_tz;
         f1          
---------------------
 2010-07-21 00:28:50
 2010-07-20 17:33:19

Timestamps are considered to be UTC.

$dt = new DateTime('Wed, 21 Jul 2010 00:28:50 GMT');
echo $dt->format('U'); // 1279672130

is the same timestamp as

$dt = new DateTime('Wed, 21 Jul 2010 02:28:50 CEST');
echo $dt->format('U'); // 1279672130

Note that the U formatting option requires PHP5.3 though. When supplying a timezone identifier in the Date String, the DateTime object recognizes the Timezone, so when you call the following on the GMT DateTime instance

echo $dt->format('Y-m-d H:i:s');

it will return 2010-07-21 00:28:50 . You can change a DateTime object's timezone with it's setTimezone() method though.

$dt = new DateTime('Wed, 21 Jul 2010 02:28:50 GMT+2');
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('Y-m-d H:i:s'); // 2010-07-21 00:28:50

But if you just need the timestamp, it's not needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM