>我从 Twitter api 获取这种形式的时间戳Fri Mar 14 18:19:26 +0000 2014
我想从这个字符串中获取月份(即 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');
试试
$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() 来解析该日期:
试试这个
$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