PHP DateTime Timezones - Constructor vs Setter Method

When using the PHP class DateTime and try setting DateTimeZone , I get different results depending on how I installed it: using DateTime::__construct or using the DateTime::setTimezone .

here is an example:

 $date = '2014-08-01' $dateTimeOne = new DateTime($date, new DateTimeZone('America/Los_Angeles')); echo $dateTimeOne->format('Ymd\TH:i:sP'); // 2014-08-01T00:00:00-07:00 $dateTimeTwo = new DateTime($date); $dateTimeTwo->setTimezone(new DateTimeZone('America/Los_Angeles')); echo $dateTimeTwo->format('Ymd\TH:i:sP'); // 2014-07-31T17:00:00-07:00 

See also http://3v4l.org/LrZfM

I looked around and did not find an adequate explanation regarding this particular behavior, except for the following comment in php docs: datetime.settimezone and php | architect Date and Time Programming Guide: Working with Time Zones - DateTimeZone .

The comment says that the DateTime::setTimezone will change the time zone for a specific point in time (timestamp), but the Unix timestamp will remain unchanged.

On the other hand, the DateTime::__construct DateTimeZone parameter is used to "overwrite the current default time zone with a user-defined" Chapter 3: Working with time zones - DateTimeZone ,

Other than that, this is not enough (what I could find).

This is what I would like to know:

  • Further explanation of these two methods for setting time zones
  • When should I use DateTime::__construct to set the time zone
  • When should I use DateTime::setTimezone to set the time zone
  • Clear example of using one vs another or how to use them together
+5
source share
1 answer

This is normal behavior.

If you do not specify the time zone in the constructor, the default time zone is used, that is, what was set using date_default_timezone_set ().

When you call:

 $dateTimeTwo->setTimezone(new DateTimeZone('America/Los_Angeles')); 

It moves the date set in the default time zone to the new time zone.


1) (constructor) set the date to 'America / Los_Angeles'
2) (setter) set the date to the default time zone, move the date to 'America / Los_Angeles'


Your default time zone was probably UTC or something close. You told the computer to install 2014-08-01 in UTC. Then you asked to switch to the America / Los_Angeles time zone, which is 7 hours earlier, thus changing the date to 2014-07-31 at 17:00.

+1
source

Source: https://habr.com/ru/post/1201793/


All Articles