group date pills when days are consecutive

This commit is contained in:
2024-07-14 01:25:44 +02:00
parent fcbd74ed34
commit 4f9d2e2bcf
2 changed files with 76 additions and 11 deletions

View File

@@ -1,4 +1,11 @@
import { isToday, isAfter, parse, compareAsc } from "date-fns";
import {
isToday,
isAfter,
parse,
compareAsc,
addDays,
isSameDay,
} from "date-fns";
import { nb } from "date-fns/locale";
import { toZonedTime, format } from "date-fns-tz";
@@ -51,3 +58,53 @@ export function isTodayOrFuture(
export function compareDates(a: Date | string, b: Date | string) {
return compareAsc(new Date(a), new Date(b));
}
export function isConsectutiveDays(a: Date, b: Date): boolean {
const nextDay = addDays(a, 1);
return isSameDay(nextDay, b);
}
export function groupConsecutiveDates(dates: string[]): string[][] {
const groupedDates: string[][] = [];
let group: string[] = [];
for (let i = 0; i < dates.length; i++) {
if (
i === 0 ||
isConsectutiveDays(toLocalTime(dates[i - 1]), toLocalTime(dates[i]))
) {
group.push(dates[i]);
} else {
groupedDates.push(group);
group = [dates[i]];
}
}
if (group.length > 0) {
groupedDates.push(group);
}
return groupedDates;
}
export function formatDateRange(dates: string[]): string {
if (dates.length === 1) {
return formatDate(dates[0], "d. MMMM");
}
const firstDate = toLocalTime(dates[0]);
const lastDate = toLocalTime(dates[dates.length - 1]);
if (firstDate.getMonth() === lastDate.getMonth()) {
// same month
return `${firstDate.getDay()}.-${lastDate.getDay()}. ${formatDate(
firstDate,
"MMMM"
)}`;
}
// continues into next month
const formattedFirstDate = formatDate(firstDate, "d. MMMM");
const formattedLastDate = formatDate(lastDate, "d. MMMM");
return `${formattedFirstDate} - ${formattedLastDate}`;
}