将ISO 8601转换为Unix时间戳

44

我如何使用PHP将2012-01-18T11:45:00+01:00 (ISO 8601) 转换为1326883500 (Unix时间戳)?

2个回答

68
这段代码将ISO 8601日期时间转换为UTC的Unix时间戳。
echo date("U",strtotime('2012-01-18T11:45:00+01:00'));

更长的版本:
$dateTime = new DateTime('2012-01-18T11:45:00+01:00');
$dateTime->setTimezone(new DateTimeZone('UTC'));
$utcTimestamp = $dateTime->getTimestamp();
echo $utcTimestamp;

谢谢,我不知道strtotime也知道ISO日期。 - 472084
在这种情况下,@Codler不需要。我认为你可能想使用另一种输入/输出格式。 - k102

22

将ISO 8601转换为Unix时间戳:

strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500

将Unix时间戳转换为ISO 8601格式(服务器时区):

date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00

将Unix时间戳转换为ISO 8601(GMT):

date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00

将Unix时间戳转换为ISO 8601(使用自定义时区):

date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00

非常有用!非常感谢! - 夏期劇場

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接