简体   繁体   English

PHP Datetime 对象和 strtotime 的时区和时间戳不正确

[英]Incorrect timezone and timestamp with PHP Datetime objects and strtotime

My server timezone is UTC, but when I create a DateTime object or when I convert a date to a timestamp with strtotime, the result is wrong.我的服务器时区是 UTC,但是当我创建 DateTime object 或使用 strtotime 将日期转换为时间戳时,结果是错误的。

I have made a simple code:我做了一个简单的代码:

$date_init = '2020-07-25 13:00:00';
$dt = new DateTime( $date_init, new DateTimeZone( 'UTC' ) );

$timezone = date_default_timezone_get();
$strtotime = strtotime( $date_init . ' UTC' );
$timestamp = $dt->getTimestamp();
$date_final = $dt->format( 'Y-m-d H:i:s P e' );

When I echo these values:当我回显这些值时:

$date_init = 2020-07-25 13:00:00
$timezone = UTC
$strtotime = 1595700000
$timestamp = 1595700000
$date_final = 2020-07-25 13:00:00 -05:00 UTC

Even the timestamp is wrong (1595700000 = 2020-07-25 18:00:00 UTC) ( online converter ).甚至时间戳也是错误的(1595700000 = 2020-07-25 18:00:00 UTC)(在线转换器)。

The expected result is:预期结果是:

$timestamp = 1595682000
$strtotime = 1595682000
$date_final = 2020-07-25 13:00:00 +00:00 UTC

I don't understand what happen, can anyone help?我不明白发生了什么,有人可以帮忙吗?

PHP version: 7.3.19 PHP 版本:7.3.19

Provide the timezone as the second parameter when creating the DateTime object.创建 DateTime object 时,提供时区作为第二个参数。

$date_init = '2020-07-25 13:00:00';
$dt = new DateTime( $date_init , new DateTimeZone("UTC"));

echo $dt->format('Y-m-d H:i:s P e');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM