fix(calendar) #263 : calculate dynamic week range for month view data loading (#264)

- Calculate exact number of weeks needed instead of fixed 6 weeks
- Compute weeks based on actual days from startDate to lastOfMonth
This commit is contained in:
lenhanphung
2025-10-29 17:26:37 +07:00
committed by GitHub
parent fc962057c0
commit 2686b13885
2 changed files with 51 additions and 4 deletions
+38
View File
@@ -0,0 +1,38 @@
import { getCalendarRange } from "../../src/utils/dateUtils";
describe("getCalendarRange", () => {
it("Nov 2025 (5 weeks): 2025-10-27 to 2025-11-30", () => {
const { start, end } = getCalendarRange(
new Date("2025-11-01T00:00:00.000Z")
);
expect(start.toISOString().slice(0, 10)).toBe("2025-10-27");
expect(end.toISOString().slice(0, 10)).toBe("2025-11-30");
});
it("Dec 2025 (6 weeks): end Sunday 2026-01-04", () => {
const { start, end } = getCalendarRange(
new Date("2025-12-01T00:00:00.000Z")
);
expect(start.toISOString().slice(0, 10)).toBe("2025-12-01");
expect(end.toISOString().slice(0, 10)).toBe("2026-01-04");
});
it("Feb 2025 (short month): end Sunday 2025-03-02", () => {
const { start, end } = getCalendarRange(
new Date("2025-02-01T00:00:00.000Z")
);
expect(start.toISOString().slice(0, 10)).toBe("2025-01-27");
expect(end.toISOString().slice(0, 10)).toBe("2025-03-02");
});
it("sets boundary times correctly (start 00:00, end 23:59)", () => {
const { start, end } = getCalendarRange(
new Date("2025-11-01T00:00:00.000Z")
);
expect(start.getHours()).toBe(0);
expect(start.getMinutes()).toBe(0);
expect(start.getSeconds()).toBe(0);
expect(end.getHours()).toBe(23);
expect(end.getMinutes()).toBe(59);
});
});
+13 -4
View File
@@ -13,13 +13,22 @@ export function getCalendarRange(date = new Date()) {
const diffToMonday = (dayOfWeekStart + 6) % 7;
const startDate = new Date(firstOfMonth);
startDate.setDate(firstOfMonth.getDate() - diffToMonday);
startDate.setHours(0, 0, 0, 0);
const lastOfMonth = new Date(year, month + 1, 0);
const dayOfWeekEnd = lastOfMonth.getDay();
const diffToSunday = (7 - dayOfWeekEnd) % 7;
const endDate = new Date(lastOfMonth);
endDate.setDate(lastOfMonth.getDate() + diffToSunday);
// Calculate how many days from startDate to lastOfMonth
const daysFromStart = Math.floor(
(lastOfMonth.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)
);
// Calculate number of weeks needed to cover all days (round up)
const weeksNeeded = Math.ceil((daysFromStart + 1) / 7);
// endDate is the Sunday of the last week (startDate + weeks * 7 - 1)
const endDate = new Date(startDate);
endDate.setDate(startDate.getDate() + weeksNeeded * 7 - 1);
endDate.setHours(23, 59, 59, 999);
return {
start: startDate,