php DateTime从今天开始,时间戳不一样

时间:2013-11-08 14:28:11

标签: php datetime

为什么从“今天”这个词创建的DateTime和代表“今天”的时间戳不相同?

$zone = 'US/Eastern';
$str = 'today';

$dt_zone = new DateTimeZone($zone);
$myDateTime = new DateTime($str, $dt_zone);

$my_stamp = $myDateTime->getTimestamp();

echo "from $my_stamp {$zone}:".$myDateTime->format('d-m-Y H:i:s') . "<br>";

我们得到的结果:来自美国/东部的1383886800:08-11-2013 00:00:00

现在让我们创建相同的代码,但是从收到的时间戳生成DateTime:

$zone = 'US/Eastern';
$str = '@1383886800';

$dt_zone = new DateTimeZone($zone);
$myDateTime = new DateTime($str, $dt_zone);

$my_stamp = $myDateTime->getTimestamp();

echo "from $my_stamp {$zone}:".$myDateTime->format('d-m-Y H:i:s') . "<br>";

我们得到了不同的结果,但时间戳相同: 我们得到的结果:从1383886800美国/东部:08-11-2013 05:00:00

可能存在从时间戳创建日期时间对象的另一种方式吗? 我可以在以后实施 $ myDateTime-&gt; modify('2 pm');并接收修改后的时间戳 (不知道如何,coz $ myDateTime-&gt; getTimestamp()在修改之前返回时间戳)

2 个答案:

答案 0 :(得分:0)

看起来它忽略了你的时区..手册有关于此的评论。但是有一种设置时间戳的方法。这将具有预期的结果

$zone = 'US/Eastern';

$dt_zone = new DateTimeZone($zone);
$myDateTime = new DateTime(null, $dt_zone);

$myDateTime->setTimestamp(1383886800); // Set from timestamp

$my_stamp = $myDateTime->getTimestamp();

echo "from $my_stamp {$zone}:".$myDateTime->format('d-m-Y H:i:s') . "\n";

答案 1 :(得分:0)

IMO,它是你在第二个例子中已经完成的输入时间戳的更好/更好的解决方案,而不是使用方法setTimestamp。您需要做的就是在{Date}对象上设置时区,调用setTimezone方法,如this demo

$myDateTime = new DateTime('@1383886800');
$myDateTime->setTimezone(new DateTimeZone('US/Eastern'));

在创建DateTime对象时忽略时区的原因是,在应用UNIX时间戳作为输入时,将使用默认时区UTC并忽略提供的时区。 See note at $timezone parameter

The $timezone parameter and the current timezone are ignored when the $time 
parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone 
(e.g. 2010-01-28T15:00:00+02:00).
相关问题