简体   繁体   中英

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.

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 ).

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

Provide the timezone as the second parameter when creating the 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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