开发者

convert any date string to timestamp without timezone

开发者 https://www.devze.com 2023-01-08 10:38 出处:网络
I\'m getting xml and rss feeds and putting the data into a database. I\'ve run into two different date formats so far...

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 (Y-m-d 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.

0

精彩评论

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