Skip to content

Commit

Permalink
fix: date-util fn
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Sep 10, 2024
1 parent 700c75c commit b2e9a6e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/fifty-eels-applaud.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zag-js/date-utils": patch
---

Fix issue where `getWeekDays` has incoherent behavior when both locale and `startOfWeekProp` are set
17 changes: 12 additions & 5 deletions packages/utilities/date-utils/src/get-start-of-week.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { type DateValue, getDayOfWeek } from "@internationalized/date"
import { type DateValue, getDayOfWeek, startOfWeek } from "@internationalized/date"

export function getStartOfWeek(date: DateValue, locale: string, firstDayOfWeek: number = 0) {
const day = getDayOfWeek(date, locale)
const diff = (day - firstDayOfWeek + 7) % 7
return date.subtract({ days: diff })
export function getStartOfWeek(date: DateValue, locale: string, firstDayOfWeek?: number) {
// If firstDayOfWeek is provided, use it; otherwise, use the locale's default
if (firstDayOfWeek !== undefined) {
// Adjust the date to the specified first day of the week
const currentDayOfWeek = getDayOfWeek(date, locale)
const daysToSubtract = (currentDayOfWeek - firstDayOfWeek + 7) % 7
return date.subtract({ days: daysToSubtract })
}

// Use the built-in startOfWeek function for locale-specific behavior
return startOfWeek(date, locale)
}
24 changes: 24 additions & 0 deletions packages/utilities/date-utils/tests/get-start-of-week.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { CalendarDate } from "@internationalized/date"
import { describe, expect, it } from "vitest"
import { getWeekDays } from "../src"

function exec(locale: string, weekStartDay?: number) {
const today = new CalendarDate(2024, 8, 21)
const days = getWeekDays(today, weekStartDay, "UTC", locale)
// console.log(days.map((d) => `${d.long} ${d.value.day}`).join(","))
return days[0].value.day
}

describe("getStartOfWeek", () => {
it("en locale", () => {
expect(exec("en")).toBe(18)
expect(exec("en", 0)).toBe(18)
expect(exec("en", 1)).toBe(19)
})

it("fr locale", () => {
expect(exec("fr")).toBe(19)
expect(exec("fr", 0)).toBe(19)
expect(exec("fr", 1)).toBe(20)
})
})

0 comments on commit b2e9a6e

Please sign in to comment.