Skip to content

Commit

Permalink
Add method and helper to round dates
Browse files Browse the repository at this point in the history
  • Loading branch information
nilshoerrmann committed Sep 6, 2021
1 parent 818a6a0 commit 80c3c34
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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', [
Expand Down

0 comments on commit 80c3c34

Please sign in to comment.