我已使用代码生成时间戳:
date_default_timezone_set("UTC");
$timestamp = date_create("now")->getTimestamp();
echo "value=$timestamp";
我得到一个值:
1484800385
我[后来]想要抓住那个值和当前时间之间的差异。
$timestamp = "1484800385";
echo " timestamp=$timestamp<hr>";
print_r (new DateTime("@$timestamp"));
echo "<hr>";
print_r (date_create("now",timezone_open("UTC")));
并输出日期 - 但时间的差异大于我的期望 - 半小时。时区也有不同的显示方式。
timestamp=1484800385
DateTime Object ( [date] => 2017-01-19 04:33:05.000000 [timezone_type] => 1 [timezone] => +00:00 )
DateTime Object ( [date] => 2017-01-19 05:08:32.000000 [timezone_type] => 3 [timezone] => UTC )
我尝试了另一个脚本。首先我生成了一个时间戳:
date_default_timezone_set("Australia/Sydney");
echo date_create("now")->getTimestamp(); // prints 1484800977
然后我复制并粘贴了几秒钟后显示的值,与现在的日期相比
date_default_timezone_set("Australia/Sydney");
$date1 = new DateTime();
$date1->setTimestamp($timestamp);
print_r($date1);
$date2 = date_create("now");
print_r($date2);
并且它仍然是错误的 - 到31分钟。
DateTime Object ( [date] => 2017-01-19 15:42:57.000000 [timezone_type] => 3 [timezone] => Australia/Sydney )
DateTime Object ( [date] => 2017-01-19 16:22:25.000000 [timezone_type] => 3 [timezone] => Australia/Sydney )
和UTC时区
$timestamp = 1484801882;
date_default_timezone_set('UTC');
$date1 = new DateTime();
$date1->setTimestamp($timestamp);
$date2 = new DateTime();
print_r($date1);
print_r($date2);
会产生相同的时区,但当前日期比我预期的时间早31分钟。
DateTime Object ( [date] => 2017-01-19 04:58:02.000000 [timezone_type] => 3 [timezone] => UTC )
DateTime Object ( [date] => 2017-01-19 05:33:23.000000 [timezone_type] => 3 [timezone] => UTC )
发生了什么?
答案 0 :(得分:0)
尝试在打印前将TimeZone设置为UTC
$UTC = new DateTimeZone("UTC");
$date = new DateTime("now");
$date->setTimezone( $UTC );
print_r ($date);
echo "<hr>";
print_r (date_create("now",timezone_open("UTC")));
输出
DateTime Object
(
[date] => 2017-01-19 05:17:52.000000
[timezone_type] => 3
[timezone] => UTC
)
>DateTime Object
(
[date] => 2017-01-19 05:17:52.000000
[timezone_type] => 3
[timezone] => UTC
)