php 将任何日期字符串转换为没有时区的时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3300141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:16:13  来源:igfitidea点击:

convert any date string to timestamp without timezone

phpsqldatetimepostgresql

提问by keith

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

我正在获取 xml 和 rss 提要并将数据放入数据库中。到目前为止,我遇到了两种不同的日期格式...

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)?

我相信还会有更多。我的日期的 postgresql 数据库是没有时区的时间戳。php 中是否有现有函数,或者是否有将任何日期字符串转换为没有时区的时间戳(Ymd H:i:s)的程序?

回答by Sarfraz

Use datewith strtotime:

使用datestrtotime

$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

回答by Matthew Wood

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

您根本不需要转换它。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

回答by Gordon

Timestamps are considered to be UTC.

时间戳被认为是 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 Uformatting 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

请注意,U格式化选项需要 PHP5.3。在日期字符串中提供时区标识符时,DateTime 对象会识别时区,因此当您在 GMT DateTime 实例上调用以下内容时

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.

它会回来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

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

但如果您只需要时间戳,则不需要。