📜 ⬆️ ⬇️

Date translation to unnamed time zone

When creating a DateTime object, you can specify a time zone in a row with time (shift in hours and minutes from GMT), for example

  new DateTime ('2009-09-30 12: 00: 00 + 0400'); 


If we have two dates that are in different time zones, then sometimes it is useful to look at the time of one date in the time zone of another. If both dates were initialized in the manner indicated above (i.e., using unnamed time zones), the error “ Can only do this ” occurs.
')
To get around it, we are doing a DateTime successor.

 class CustomDateTime extends DateTime {
 
     public function setTimezone ($ dtz) {
         if (! preg_match ('/ ^ [0-9 \ + \ -] /', $ dtz-> getName ())) {
             return parent :: setTimezone ($ dtz);
         }
 
         $ offset = $ dtz-> getOffset ($ this) - $ this-> getTimezone () -> getOffset ($ this);
 
         $ this-> modify ($ offset. 'second');
 
         $ format = $ this-> format ('Ymd H: i: s').  $ dtz-> getName ();
         $ this -> __ construct ($ format);
     }
 }


and with pleasure we use it:

     public function testApplyUnnamedTimezoneToOtherDateTime () {
         $ dt1 = new CustomDateTime ('2009-09-30T12: 00: 00-02: 00');
         $ dt2 = new CustomDateTime ('2009-09-30T12: 00: 00 + 02: 00');
 
         $ dt2-> setTimezone ($ dt1-> getTimezone ());

         $ this-> assertEquals ('2009-09-30T08: 00: 00-02: 00', $ dt2-> format ('c'));
     }

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


All Articles