Example #1
0
 /**
  * Return the difference in seconds.
  *
  * @param MomentPHP|\DateTime|string|int $dateTime
  * @param string $unit
  * @param bool $asFloat
  * @return int
  * @throws InvalidArgumentException
  */
 public function diff($dateTime, $unit = self::SECONDS, $asFloat = false)
 {
     if ($dateTime instanceof MomentPHP) {
         $diffMoment = $dateTime;
     } elseif ($dateTime instanceof \DateTime || is_string($dateTime) || is_int($dateTime)) {
         $diffMoment = new self($dateTime);
     } else {
         throw new InvalidArgumentException('Invalid type of datetime to difference.');
     }
     $unit = $this->normalizeUnits($unit);
     if ($unit === self::YEARS || $unit === self::MONTHS) {
         // average number of days in the months in the given dates
         $avgSecondsInMonth = ((int) $this->daysInMonth() + (int) $diffMoment->daysInMonth()) / 2 * 24 * 60 * 60;
         $differenceMonths = ((int) $this->years() - (int) $diffMoment->years()) * 12 + ((int) $this->months() - (int) $diffMoment->months());
         $cloneThis = clone $this;
         $cloneDiffMoment = clone $diffMoment;
         $differenceDays = ($this->timestamp() - $cloneThis->startOf(self::MONTHS)->timestamp() - ($diffMoment->timestamp() - $cloneDiffMoment->startOf(self::MONTHS)->timestamp())) / $avgSecondsInMonth;
         $differenceTimezone = ($this->timezoneOffset() - $cloneThis->startOf(self::MONTHS)->timezoneOffset() - ($diffMoment->timezoneOffset() - $cloneDiffMoment->startOf(self::MONTHS)->timezoneOffset())) / $avgSecondsInMonth;
         $difference = $differenceMonths + $differenceDays - $differenceTimezone;
         if ($unit === self::YEARS) {
             $difference /= 12;
         }
     } else {
         $difference = $this->timestamp() - $diffMoment->timestamp();
         switch ($unit) {
             case self::MINUTES:
                 $difference /= 60;
                 break;
             case self::HOURS:
                 $difference /= 60 * 60;
                 break;
             case self::DAYS:
                 $difference /= 24 * 60 * 60;
                 break;
         }
     }
     $difference = $asFloat ? round($difference, 2) : (int) floor($difference);
     return $difference;
 }