/** * Calculates a difference between two dates * @see http://www.php.net/manual/en/datetime.diff.php * @param integer $datetime1 * @param integer $datetime2 * @param boolean $absolute * @return string Something like this: 1 year. 2 mon. 6 day. 4 hours. 21 min. 10 sec. */ public static function diffAsText($datetime1, $datetime2, $absolute = false) { if (!$datetime1 instanceof \DateTimeInterface) { $datetime1 = new static($datetime1); } if (!$datetime2 instanceof \DateTimeInterface) { $datetime2 = new static($datetime2); } $interval = $datetime1->diff($datetime2, $absolute); $str = ''; $str .= $interval->y ? $interval->y . ' year. ' : ''; $str .= $interval->m ? $interval->m . ' mon. ' : ''; $str .= $interval->d ? $interval->d . ' day. ' : ''; $str .= $interval->h ? $interval->h . ' hour. ' : ''; $str .= $interval->i ? $interval->i . ' min. ' : ''; $str .= $interval->s || $str === '' ? $interval->s . ' sec. ' : ''; return rtrim($str); }
/** * Convenience method for getting the remaining time from a given time. * * @param \DateTime|\DateTimeImmutable $datetime The date to get the remaining time from. * @return \DateInterval|bool The DateInterval object representing the difference between the two dates or FALSE on failure. */ public static function fromNow($datetime) { $timeNow = new static(); return $timeNow->diff($datetime); }
/** * Convert number of seconds into a DateInterval object. * * @param int $seconds Number of seconds to parse * @return DateInterval * @see DateInterval https://php.net/DateInterval */ public static function secondsToInterval($seconds) { $epoch = new static('@0'); return $epoch->diff(new static("@{$seconds}")); }