@Bromomb
您的函数运行良好,但您忘记了一件事。
对于 01.01.1970 之前的日期,时间戳可能为负数,因此我们需要不同的正则表达式
我用过这个,效果很好:
preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);
最后,我稍微修改了您的功能,使其对我更有用。
现在我可以决定是否将日期返回为
- "date" => 仅日期
- "time" => 仅时间
- "datetime" => 日期和时间
- "array" => 日期和时间作为一个数组
- "string" => 时间戳作为字符串
当我给出第三个参数时,我可以决定是否要添加/减去与 UTC 时区的差异...
function parseJsonDate($date, $type = 'date', $utc = 0) {
// Match the time stamp (microtime) and the timezone offset (may be + or -) and also negative Timestamps
preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);
$seconds = $matches[1]/1000; // microseconds to seconds
$UTCSec = $matches[2]/100*60*60; // utc timezone difference in seconds
if($utc != 0){
$seconds = $seconds + $UTCSec; // add or divide the utc timezone difference
}
$date = date( 'Y-m-d', $seconds ); // only date
$dateTime = date( 'Y-m-d H:i:s', $seconds ); // date and time
$time = date( 'H:i:s', $seconds ); // only time
switch($type)
{
case 'date':
return $date; // returns 'YYYY-MM-DD'
break;
case 'datetime':
return $dateTime; // returns 'YYYY-MM-DD HH:ii:ss'
break;
case 'time':
return $time; // returns 'HH:ii:ss'
break;
case 'array':
$dateArray = str_replace(" ", "-", $dateTime);
$dateArray = str_replace(":", "-", $dateArray);
return explode('-', $dateArray); // return array('YYYY', 'MM', 'DD', 'HH', 'ii', 'SS')
break;
case 'string':
return $matches[1] . $matches[2]; // returns 1336197600000-0600
break;
}
}