【问题标题】:convert any date string to timestamp without timezone将任何日期字符串转换为没有时区的时间戳
【发布时间】:2011-03-19 00:38:47
【问题描述】:
我正在获取 xml 和 rss 提要并将数据放入数据库。到目前为止,我遇到了两种不同的日期格式...
Wed, 21 Jul 2010 00:28:50 GMT
和
2010-07-20T17:33:19Z
我相信还会有更多。我的 postgresql 数据库的日期是没有时区的时间戳。 php中是否存在现有函数,或者是否有将任何日期字符串转换为没有时区(Y-m-d H:i:s)的时间戳的程序?
【问题讨论】:
标签:
php
sql
datetime
postgresql
【解决方案1】:
将date 与strtotime 一起使用:
$date = date('Y-m-d H:i:s', strtotime('Wed, 21 Jul 2010 00:28:50 GMT'));
echo $date;
结果:
2010-07-21 05:28:50
.
$date = date('Y-m-d H:i:s', strtotime('2010-07-20T17:33:19Z'));
echo $date;
结果:
2010-07-20 22:33:19
【解决方案2】:
时间戳被视为 UTC。
$dt = new DateTime('Wed, 21 Jul 2010 00:28:50 GMT');
echo $dt->format('U'); // 1279672130
与
的时间戳相同
$dt = new DateTime('Wed, 21 Jul 2010 02:28:50 CEST');
echo $dt->format('U'); // 1279672130
请注意,U 格式化选项需要 PHP5.3。在日期字符串中提供时区标识符时,DateTime 对象会识别时区,因此当您在 GMT DateTime 实例上调用以下内容时
echo $dt->format('Y-m-d H:i:s');
它将返回2010-07-21 00:28:50。不过,您可以使用 setTimezone() 方法更改 DateTime 对象的时区。
$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
但如果您只需要时间戳,则不需要。
【解决方案3】:
您根本不需要转换它。 PostgreSQL 应该会自动转换:
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
【讨论】:
-
有关 Postgres 识别的日期/时间格式的详细信息 here。