使用php将日期和时间转换为时间戳的最佳方法是什么?

时间:2012-06-28 03:12:33

标签: php timestamp strtotime

我需要使用php将日期和时间(GMT)转​​换为时间戳。以下代码显示了我目前正在使用的内容:

<?php
$date="2012-06-29 10:50";
$timestamp = strtotime($date);
echo $timestamp;
?>

但是,当我测试在线转换器(http://www.epochconverter.com)中的时间戳时,生成的日期是2012年6月29日,格林尼治标准时间8:50或之前2小时。 strtotime()函数可能不完全准确,只是估计时间吗?如果是这样,有没有更好的方法可以用来获得确切的时间?

感谢。

1 个答案:

答案 0 :(得分:0)

strtotime假设您要在服务器的本地时间转换字符串,因此如果服务器时区是两个小时,则结果将为wll。

the manual中的评论提出了几个解决方案,您可以将UTC附加到您的日期:

$timestamp = strtotime($date.' UTC');

或者您可以更改脚本的默认时区(这将适用于所有其他时间函数!):

date_default_timezone_set('UTC');
$timestamp = strtotime($date);

作为最后的替代方案,您可以尝试date_create_from_format,它允许您指定字符串的格式:

$datetime = date_create_from_format('Y-m-d H:i', $date, new DateTimeZone('UTC'));

$timestamp = date_format($datetime, 'U');
// Alternatively (thanks Herbert) - 5.3+ only
$timestamp = date_timestamp_get($datetime);