date_create_from_format()的问题

时间:2014-03-25 17:24:27

标签: php parsing date

我正在使用插件从twitter Feed创建wordpress帖子,我正在尝试编辑它,因此发布时间与推文时间相同,而不是cron运行的时间。

不幸的是,twitter的API返回一个已格式化的日期字符串,而不是时间戳,所以我不得不解析它,然后以wordpress友好格式保存它。

// Wed Jun 06 20:07:10 +0000 2012  (Twitter formatted date example)
// 2014-03-10 18:30:26             (Wordpress formatted date example)
$tweet_date = $tweet->created_at;
$tweet_date = date_create_from_format("D M d h:i:s O Y", $tweet_date);
$tweet_date = date("Y-m-d h:i:s", $tweet_date);

不幸的是,我从Unix Epoch(1970年1月1日)获得的所有内容。

我知道我必须错过一步,但我无法弄清楚在哪里。

3 个答案:

答案 0 :(得分:3)

你有两个问题:

1)当您在{24}小时内表示h时,您使用H几个小时 2)使用date_format()时需要使用date_create_from_format(),因为该函数返回与date()不兼容的DateTime对象

$tweet_date = date_create_from_format("D M d H:i:s O Y", 'Wed Jun 06 20:07:10 +0000 2012');
echo date_format($tweet_date, 'Y-m-d H:i:s');

See it in action

答案 1 :(得分:1)

问题在于您在PHP的旧式和新式日期处理之间进行混合和匹配。

date_create_from_format()是较新API的一部分,并输出DateTime对象,而不是旧date()函数所期望的时间戳整数。

理想情况下,您应该完全使用新的或旧的日期功能。你可以在它们之间切换,但通常不需要。

例如,在您的情况下,DateTime生成的date_create_from_format()对象附加了一个完全可用的format()方法,与date()完全相同函数,但在DateTime对象上。

$tweet_date_object = date_create_from_format("D M d h:i:s O Y", $tweet_date);
$tweet_date = $tweet_date_object->format("Y-m-d h:i:s");

答案 2 :(得分:0)

以下链接可能会有所帮助。

http://codex.wordpress.org/Formatting_Date_and_Time