如何转换日期字符串 Mon, 24 May 2010 17:54:00 GMT 从RSS进料到PHP的时间戳?

有帮助吗?

解决方案

您可以使用内置功能 strtotime(). 。它将日期字符串作为第一个参数,并返回UNIX时间戳。

http://php.net/manual/en/function.strtotime.php

其他提示

试试这个:

$pubDate = $item->pubDate;
$pubDate = strftime("%Y-%m-%d %H:%M:%S", strtotime($pubDate));

strtotime 不适用于不同的时区。

我刚刚编写了此功能,以将RSS Pubdates转换为时间戳,这确实考虑到了不同的时区:

function rsstotime($rss_time) {
    $day       = substr($rss_time, 5, 2);
    $month     = substr($rss_time, 8, 3);
    $month     = date('m', strtotime("$month 1 2011"));
    $year      = substr($rss_time, 12, 4);
    $hour      = substr($rss_time, 17, 2);
    $min       = substr($rss_time, 20, 2);
    $second    = substr($rss_time, 23, 2);
    $timezone  = substr($rss_time, 26);

    $timestamp = mktime($hour, $min, $second, $month, $day, $year);

    date_default_timezone_set('UTC');

    if(is_numeric($timezone)) {
        $hours_mod    = $mins_mod = 0;
        $modifier     = substr($timezone, 0, 1);
        $hours_mod    = (int) substr($timezone, 1, 2);
        $mins_mod     = (int) substr($timezone, 3, 2);
        $hour_label   = $hours_mod > 1 ? 'hours' : 'hour';
        $strtotimearg = $modifier . $hours_mod . ' ' . $hour_label;
        if($mins_mod) {
            $mins_label = $mins_mod > 1 ? 'minutes' : 'minute';
            $strtotimearg .= ' ' . $mins_mod . ' ' . $mins_label;
        }
        $timestamp = strtotime($strtotimearg, $timestamp);
    }

    return $timestamp;
}

如果RSS feed中的PubDate具有除时区,则rsstotime()函数无法正常工作 +0000. 。问题在于$修饰符,必须逆转。要修复必须添加两行的,因此该行:

$modifier = substr($timezone, 0, 1); 

变成:

$modifier = substr($timezone, 0, 1);        
if($modifier == "+"){ $modifier = "-"; } else
if($modifier == "-"){ $modifier = "+"; }

只是为了澄清修改 - 例如 PubDate 曾是 2013年5月22日,星期三17:09:36 +0200 然后行

$timestamp = strtotime($strtotimearg, $timestamp

将时间抵消了两个小时,没有将其重置为 +0000 时区预期。

2013年5月22日,星期三17:09:36 +0200 显示此处介绍的时间是在TimeZone GMT +2中。

该代码无法正常工作,并在时间上增加了两个小时,因此时间变成了 2013年5月22日,星期三19:09:36 +0000, , 反而 2013年5月22日,星期三15:09:36 +0000 正如本应的那样。

function pubdatetotime($pubDate) {

$months = array('Jan' => '01', 'Feb' => '02', 'Mar' => '03', 
'Apr' => '04', 'May' => '05', 'Jun' => '06', 
'Jul' => '07', 'Aug' => '08', 'Sep' => '09', 
'Oct' => '10', 'Nov' => '11', 'Dec' => '12');

$date = substr($pubDate, 5,11);
$year = substr($date, 7,4); 
$month = substr($date, 3,3);
$d =  substr($date, 0,2);

$time = substr($pubDate, 17,8);

return $year."-".$months[$month]."-".$d." ".$time;  
}

尝试此功能

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top