Add param to timeUntil() to require time output

If the time specified in timeUntil() is at least 3 days in the future,
the output will only contain the month and the day. With $requireTime it
will also ouput the time. This is useful for some views, e.g.
scheduled downtimes.
This commit is contained in:
Eric Lippmann 2019-07-11 13:03:04 +02:00
parent 902e5d1cb8
commit 1351be7da8
2 changed files with 9 additions and 7 deletions

View File

@ -40,10 +40,11 @@ class DateFormatter
* Get the diff between the given time and the current time * Get the diff between the given time and the current time
* *
* @param int|float $time * @param int|float $time
* @param bool $requireTime
* *
* @return array * @return array
*/ */
protected static function diff($time) protected static function diff($time, $requireTime = false)
{ {
$invert = false; $invert = false;
$now = time(); $now = time();
@ -56,9 +57,9 @@ class DateFormatter
if ($diff > 3600 * 24 * 3) { if ($diff > 3600 * 24 * 3) {
$type = static::DATE; $type = static::DATE;
if (date('Y') === date('Y', $time)) { if (date('Y') === date('Y', $time)) {
$formatted = date('M j', $time); $formatted = date($requireTime ? 'M j H:i' : 'M j', $time);
} else { } else {
$formatted = date('Y-m', $time); $formatted = date($requireTime ? 'Y-m-d H:i' : 'Y-m', $time);
} }
} else { } else {
$minutes = floor($diff / 60); $minutes = floor($diff / 60);
@ -219,12 +220,13 @@ class DateFormatter
* *
* @param int|float $time * @param int|float $time
* @param bool $timeOnly * @param bool $timeOnly
* @param bool $requireTime
* *
* @return string * @return string
*/ */
public static function timeUntil($time, $timeOnly = false) public static function timeUntil($time, $timeOnly = false, $requireTime = false)
{ {
list($type, $until, $invert) = static::diff($time); list($type, $until, $invert) = static::diff($time, $requireTime);
if ($invert && $type === static::RELATIVE) { if ($invert && $type === static::RELATIVE) {
$until = '-' . $until; $until = '-' . $until;
} }

View File

@ -60,13 +60,13 @@ $this->addHelperFunction('timeSince', function ($time, $timeOnly = false) {
); );
}); });
$this->addHelperFunction('timeUntil', function ($time, $timeOnly = false) { $this->addHelperFunction('timeUntil', function ($time, $timeOnly = false, $requireTime = false) {
if (! $time) { if (! $time) {
return ''; return '';
} }
return sprintf( return sprintf(
'<span class="relative-time time-until" title="%s">%s</span>', '<span class="relative-time time-until" title="%s">%s</span>',
DateFormatter::formatDateTime($time), DateFormatter::formatDateTime($time),
DateFormatter::timeUntil($time, $timeOnly) DateFormatter::timeUntil($time, $timeOnly, $requireTime)
); );
}); });