Skip to content

Fix Week formatting issue when date range spans across two years #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions src/Trend.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public function mapValuesToDates(Collection $values): Collection

$placeholders = $this->getDatePeriod()->map(
fn (CarbonInterface $date) => new TrendValue(
date: $date->format($this->getCarbonDateFormat()),
date: $date->format($this->getCarbonDateFormat($date)),
aggregate: 0,
)
);
Expand Down Expand Up @@ -180,16 +180,23 @@ protected function getSqlDate(): string
return $adapter->format($this->dateColumn, $this->interval);
}

protected function getCarbonDateFormat(): string
{
return match ($this->interval) {
'minute' => 'Y-m-d H:i:00',
'hour' => 'Y-m-d H:00',
'day' => 'Y-m-d',
'week' => 'Y-W',
'month' => 'Y-m',
'year' => 'Y',
protected function getCarbonDateFormat(CarbonInterface $date): string
{
return (match ($this->interval) {
'minute' => fn() => 'Y-m-d H:i:00',
'hour' => fn() => 'Y-m-d H:00',
'day' => fn() => 'Y-m-d',
'week' => function(CarbonInterface $date) {
// Handle the special case for week 53 of the year
// when the week starts in December and ends in January of the next year.
if ($date->week === 1 && $date->month === 12 && $this->interval === 'week') {
return 'Y-53';
}
return 'Y-W';
},
'month' => fn() => 'Y-m',
'year' => fn() => 'Y',
default => throw new Error('Invalid interval.'),
};
})($date);
}
}