Example #1
0
 /** Diff two date objects. Only full units are returned */
 public static function diff(TimeInterval $interval, Date $date1, Date $date2) : int
 {
     if ($date1->getOffsetInSeconds() != $date2->getOffsetInSeconds()) {
         // Convert date2 to same timezone as date1. To work around PHP bug #45038,
         // not just take the timezone of date1, but construct a new one which will
         // have a timezone ID - which is required for this kind of computation.
         $tz = new TimeZone(timezone_name_from_abbr('', $date1->getOffsetInSeconds(), $date1->toString('I')));
         // Now, convert both dates to the same time (actually we only need to convert the
         // second one, as the first will remain in the same timezone)
         $date2 = $tz->translate($date2);
     }
     // Then cut off timezone, by setting both to GMT
     $date1 = DateUtil::setTimeZone($date1, new TimeZone('GMT'));
     $date2 = DateUtil::setTimeZone($date2, new TimeZone('GMT'));
     switch ($interval) {
         case TimeInterval::$YEAR:
             return -($date1->getYear() - $date2->getYear());
         case TimeInterval::$MONTH:
             return -(($date1->getYear() - $date2->getYear()) * 12 + ($date1->getMonth() - $date2->getMonth()));
         case TimeInterval::$DAY:
             return -(intval($date1->getTime() / 86400) - intval($date2->getTime() / 86400));
         case TimeInterval::$HOURS:
             return -(intval($date1->getTime() / 3600) - intval($date2->getTime() / 3600));
         case TimeInterval::$MINUTES:
             return -(intval($date1->getTime() / 60) - intval($date2->getTime() / 60));
         case TimeInterval::$SECONDS:
             return -($date1->getTime() - $date2->getTime());
     }
 }
Example #2
0
 /**
  * Move a date to a given timezone. Does not modify the date's
  * actual value.
  *
  * @param   util.Date date
  * @param   util.TimeZone tz
  * @return  util.Date
  */
 public static function moveToTimezone(Date $date, TimeZone $tz)
 {
     return $tz->translate($date);
 }
Example #3
0
 /**
  * Format a date by the given strftime()-like format string.
  *
  * These format tokens are not supported intentionally:
  * %a, %A, %b, %B, %c, %h, %p, %U, %x, %X
  *
  * @see     php://strftime
  * @param   string format
  * @param   util.TimeZone outtz default NULL
  * @return  string
  * @throws  lang.IllegalArgumentException if unsupported token has been given
  */
 public function format($format, TimeZone $outtz = NULL)
 {
     return preg_replace_callback('#%([a-zA-Z%])#', array($outtz === NULL ? $this : $outtz->translate($this), 'formatCallback'), $format);
 }