PHP timestamp conversion with DateTime::createFromFormat()

拜拜、爱过 提交于 2021-02-10 13:01:26

问题


This code:

$timestamp = 1423522800;  // Timestamp for 2015-02-10
$date1 = DateTime::createFromFormat('U', $timestamp);

echo $date1->format('d/m/Y H:i') . "\n";
echo $date1->format('U') . "\n\n";

$date2 = new DateTime('2015-02-10');

echo $date2->format('d/m/Y H:i') . "\n";
echo $date2->format('U') . "\n";

Gives me this output:

09/02/2015 23:00
1423522800

10/02/2015 00:00
1423522800

What the hell is going on?

I think it's timezone related, but from the DateTime::createFromFormat() documentation:

Note: The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

I'm using PHP 5.5.9-1ubuntu4.5


回答1:


When a DateTime object from a UNIX timestamp with

$timestamp = 1423522800;  // Timestamp for 2015-02-10
$date1 = DateTime::createFromFormat('U', $timestamp);

or

$date1 = new DateTime('@'.$timestamp);

or

$date1 = date_create('@'.$timestamp);

is created, the time zone of the object is always +00:00 or UTC. Even if a time zone is specified when the object is created, this is ignored when a timestamp is used.

$timestamp = 1423522800;  // Timestamp for 2015-02-10
$date1 = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('Europe/Madrid'));

var_dump($date1);

Output:

object(DateTime)#3 (3) {
  ["date"]=>
  string(26) "2015-02-09 23:00:00.000000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+00:00"
}

To get the local time, the time zone has to be set after the DateTime has been created.

$date = date_create('@1423522800')
  ->setTimeZone(new DateTimeZone('Europe/Madrid'));

var_dump($date);

Now the object has the expected time and time zone.

object(DateTime)#2 (3) {
  ["date"]=>
  string(26) "2015-02-10 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Madrid"
}


来源:https://stackoverflow.com/questions/28437193/php-timestamp-conversion-with-datetimecreatefromformat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!