From 80c3c34558f572b6f1b921ee36d99f719726338b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nils=20Ho=CC=88rrmann?= Date: Mon, 6 Sep 2021 11:26:23 +0200 Subject: [PATCH] Add method and helper to round dates --- index.php | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/index.php b/index.php index 26fb458..bca1d5a 100755 --- a/index.php +++ b/index.php @@ -71,6 +71,13 @@ return $from->diff($to); }, + 'toDateRounded' => function ( + $field, + $interval = 'PT5M', + $reference = 'midnight' + ) { + return dateRounded($field->value(), $interval, $refernce); + }, 'toFormatted' => function ( $field, $datetype = IntlDateFormatter::LONG, @@ -312,6 +319,45 @@ function dateFormatted( return $formatter->format(datetime($datetime)); } +function dateRounded($date, $interval = 'PT5M', $reference = null) +{ + $date = new DateTimeImmutable($date); + $interval = new DateInterval($interval); + + if (!$reference) { + if ($interval->y > 0) { + $century = floor($date->format('Y') / 100) * 100; + $reference = '00:00:00 first day of January ' . $century; + } elseif ($interval->m > 0) { + $reference = '00:00:00 first day of January this year'; + } elseif ($interval->d > 0) { + $reference = '00:00:00 first day of this month'; + } else { + $reference = '00:00:00'; + } + } + + $start = $date->modify($reference); + $end = $date->add($interval); + + $period = new DatePeriod($start, $interval, $end); + $timestamp = $date->getTimestamp(); + $normalized = null; + foreach ($period as $occurence) { + $current = $occurence->getTimestamp(); + if ( + !$normalized || + abs($timestamp - $current) < abs($timestamp - $normalized) + ) { + $normalized = $current; + } + } + + $result = new DateTime(); + + return $result->setTimestamp($normalized); +} + function dateRange($from = [null, null], $to = [null, null]) { $options = option('hananils.date-methods', [