从timestamp字符串获取date,month.year

时间:2014-04-05 05:38:42

标签: php datetime

我正在以这种形式Fri Mar 14 18:19:26 +0000 2014

从twitter api获取时间戳

我希望从这个字符串获得一个月(即3,4,12等)。

这是代码。有什么问题呢? :

<?php

            $time = "Fri Mar 14 18:19:26 +0000 2014";
            $dt = new DateTime('@' . strtotime($time));
            $tweet_time = $dt->format('H:m:s');
            $tweet_dtm = $dt->format('Y:m:d');
            $year =  $dt->format('Y'); 
            $month =  $dt->format('m'); 
?>

它给出了运行时错误

我不明白这里发生了什么。这段代码在三月份工作正常,我没有做出改变,即使它在四月份测试时也开始出错。任何不满?

请参阅http://ideone.com/z2zmmV

更新

当我在Ideone上测试时,这两个答案都有效,但是当我在我的代码中使用它时,它会给出错误:

            foreach($tweets5 as $item)
            {
                    $text = $item->text;
        $text_id = $item->id;
                    $user_id = $item->user->id;
                    $name = $item->user->name;
        $constant = 'retweet';
        $time = $item->created_at;
                    //Up to this execution goes fine. After that it stop. any php adons which gives line no of error?
        $dt = new DateTime($time);
        $tweet_time = $dt->format('H:m:s');
        $tweet_dtm = $dt->format('Y:m:d');
        $year =  $dt->format('Y'); 
        $month =  $dt->format('m'); 

2 个答案:

答案 0 :(得分:1)

$time = "Fri Mar 14 18:19:26 +0000 2014";
            $dt = new DateTime($time);
            $tweet_time = $dt->format('H:m:s');
            $tweet_dtm = $dt->format('Y:m:d');
           echo $year =  $dt->format('Y'); 
           echo $month =  $dt->format('m'); 
//output 2014 03

您需要使用DateTime::createFromFormat()来解析该日期:

答案 1 :(得分:1)

试试这个

$date = DateTime::createFromFormat('D M d H:i:s e Y', 'Fri Mar 14 18:19:26 +0000 2014');
echo $date->format('Y-m-d'); //2014-03-14
echo $date->format('Y'); //2014
echo $date->format('m'); //03
echo $date->format('d'); //14