String to DateTime转换从初始时间开始减少1小时

时间:2015-04-01 13:25:28

标签: php datetime

$initialTime = "31.03.2015 17:59";
$timeStamp = (new IntlDateFormatter('en_US', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'Europe/Moscow', IntlDateFormatter::GREGORIAN,'dd.MM.yyyy HH:mm'))->parse($initialTime);
$dt = new DateTime('@'.$timeStamp.' UTC');
$dt->setTimezone(new DateTimeZone('Europe/Moscow')); 
var_dump($dt);

所以,从$initialTime我使用$timeStamp获得IntlDateFormatter::parse()(时区为'Europe/Moscow'

然后我将$timeStamp解析为DateTime并将其时区设置为相同,但输出:

class DateTime#1 (3) {
  public $date =>
  string(19) "2015-03-31 16:59:00"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(13) "Europe/Moscow"
}

为什么初始时间与输出时间相差一小时?

1 个答案:

答案 0 :(得分:0)

IntlDateFormatter看起来有问题。来自Timestamp对象的DateTime与已解析的对象不同。

$initialDate = new DateTime();
$initialDate->setTimeZone(new DateTimeZone('Europe/Moscow'));
$initialTime =$initialDate->format('d.m.Y H:i');
echo $initialTime, "\n";
echo "Real timestamp: ", $initialDate->getTimestamp(), "\n";
$timeStamp = (new IntlDateFormatter('ru_RU', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'Europe/Moscow', IntlDateFormatter::GREGORIAN,'dd.MM.yyyy HH:mm'))->parse($initialTime);
echo "Parsed timestamp: ", $timeStamp, "\n";

输出:

01.04.2015 16:39
Real timestamp:   1427895596
Parsed timestamp: 1427891940