Answer the question
In order to leave comments, you need to log in
How to split a date range into months, days or years?
It is necessary, depending on the range of dates, to break into days, months or years
. I need data to build a graph. Displaying every day will be too much, but in such a way that it scales, where to display by months, and where by days ...
Answer the question
In order to leave comments, you need to log in
https://3v4l.org/6J5f5
<?php
function date_period_grid($start, $end)
{
$start = new DateTime($start);
$end = new DateTime($end);
$interval = $end->diff($start);
$days = $interval->days;
$months = $interval->y * 12 + $interval->m;
$years = intval($end->format('Y')) - intval($start->format('Y'));
if ($years > 1) {
$period = new DatePeriod($start, new DateInterval('P1Y'), $years);
$format = 'Y';
} elseif ($months > 1) {
$period = new DatePeriod($start, new DateInterval('P1M'), $months);
$format = 'm.Y';
} else {
$period = new DatePeriod($start, new DateInterval('P1D'), $days);
$format = 'd.m.Y';
}
$result = [];
foreach ($period as $date) {
$result[] = $date->format($format);
}
return $result;
}
date_period_grid('2012-07-01', '2015-11-01');
// => ['2012', '2013', '2014', '2015']
date_period_grid('2015-01-01', '2015-11-01');
// => ['01.2015', '02.2015', ..., '11.2015']
date_period_grid('2015-10-01', '2015-11-01');
// => ['01.10.2015', '02.10.2015', ..., '01.11.2015']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question