简体   繁体   中英

PHP have result different timezone two datetime

Php version: 5.5.9-1ubuntu4.5

php.ini related configuration:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
;date.timezone = UTC

My PHP code:

<?php
$datetime1 = new DateTime('2009-10-01 00:00:00');
$datetime2 = new DateTime('2009-11-01 00:00:00');
echo $datetime1->format('c') . '<br/>';
echo $datetime2->format('c') . '<br/>';

when I access that code from browser, I get this result:

2009-10-01T00:00:00+08:00
2009-11-01T00:00:00+07:00

My question: Why that two dates above has different timezone?

When I set that date.timezone to UTC or other timezone, the code result above will give correct timezone value.

Daylight saving time. In your local timezone, daylight saving time apparently ended sometime in October, sending the clocks back one hour, and changing your time offset relative to UTC.

Your Server time is not set to UTC and your php.ini is not set to use UTC, so you are getting whatever time your server is set to.

This section of your php.ini file:-

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
;date.timezone = UTC

Should look like this:-

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = UTC

Notice that the colon has been deleted from the start of the line. The colon indicates that the rest of the line is a comment and should be ignored.

If you make this change and re-start Apache, PHP will now always work in UTC and your test code will work as expected.

If you can, you should set your server timezone to UTC too.

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