我在PHP中有一个日期字符串,比如$min_date = "2012-03-30"
如果我通过javascript Date.UTC函数运行这个日期,我会得到1333065600000。这就是我想要的值。
var split_date = min_date.split('-');
Date.UTC(split_date[0],(parseInt(split_date[1])-1),split_date[2]); //gives 1333065600000
我无法在 PHP 中获取此值。
strtotime($min_date); //gives 1333045800
mktime(23,60,60,intval($split_date[1]),intval($split_date[2]),intval($split_date[0])); //gives 1333132260
如何从 PHP 中获取我在 JavaScript 中获得的值?我宁愿在服务器端进行此转换并将其发送给客户端,因为这些日期来自一个大数组,在客户端转换会很痛苦。
PS:我的服务器时间设置正确。
由于时区差异,您在PHP中无法获得正确的时间戳。将时区设置为 UTC,您将拥有与 javascript 相同的输出:
# globally
date_default_timezone_set('UTC');
echo strtotime('2012-03-30') . "'n";
# or like @Jim said, only for single operation :
echo strtotime('2012-03-30 UTC') . "'n";
更好的解决方案是使用日期时间类:
$dt = new DateTime($date, new DateTimeZone('UTC'));
echo $dt->getTimestamp() . "'n";
<script>
var serverTime = new Date("<?php echo date('M d, Y H:i:s') ?>");
</script>
正如格拉维奇所提到的,这是由于您的时区不是UTC。
全局更改时区设置的替代方法是简单地将 UTC 传递到 strtotime:
strtotime($min_date. " UTC");
这是因为您的时区设置不正确。您需要将时区设置为 UTC。然后,您可以使用DateTime
类并获取所需的时间戳,如下所示:
$date = new DateTime('30-03-2012', new DateTimeZone('UTC'));
$ts = $date->getTimestamp()*1000;
echo $ts;
输出:
1333065600000
演示!