Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(core): introduce PlainDate and eliminate Date usage in Calendar internals (#2291)

Andrey Goder1fc21407ee36
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index 2694580303..45644f0cae 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -41,37 +41,31 @@ import {
dayCellTheme,
} from './styles';
import {
- dateToISO,
- parseISO,
- isSameDay,
- isDateInRange,
- getWeekNumber,
- formatAccessibleDate,
-} from './utils';
+ type PlainDate,
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateToDate,
+ plainDateFromDate,
+ plainDateToday,
+ plainDateSetFirstOfMonth,
+ plainDateAddMonths,
+ plainDateAddDays,
+ plainDateIsBefore,
+ plainDateIsEqual,
+ plainDateIsInRange,
+ plainDateGetWeekNumber,
+ plainDateFormat,
+ DATE_FORMAT_WITH_WEEKDAY,
+ DATE_FORMAT_MONTH_YEAR,
+} from '../utils/plainDate';
import {xdsClassName, mergeProps} from '../utils';
// =============================================================================
// Types
// =============================================================================
-/**
- * ISO 8601 date string in YYYY-MM-DD format.
- * Example: "2026-01-28"
- */
-
-export type ISODateString =
- `${number}${number}${number}${number}-${number}${number}-${number}${number}`;
-
-/** Day of week: 0 = Sunday through 6 = Saturday */
-
-export type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
-
-/** Date range with start and end dates */
-
-export interface DateRange {
- start: ISODateString;
- end: ISODateString;
-}
+export type {ISODateString, DayOfWeek, DateRange} from '../utils/dateTypes';
+import type {ISODateString, DayOfWeek, DateRange} from '../utils/dateTypes';
/** Imperative handle for XDSCalendar ref */
@@ -204,7 +198,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
} = props;
// Today's date (memoized)
- const today = useMemo(() => new Date(), []);
+ const today = useMemo(() => plainDateToday(), []);
// Internal state for uncontrolled mode
const [internalValue, setInternalValue] = useState<
@@ -225,25 +219,25 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
const effectiveValue = value !== undefined ? value : internalValue;
// Focus date state (which month is visible)
- const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
+ const [internalFocusDate, setInternalFocusDate] = useState<PlainDate>(() => {
if (focusDateProp) {
- return parseISO(focusDateProp);
+ return plainDateFromISO(focusDateProp);
}
if (effectiveValue) {
if (typeof effectiveValue === 'string') {
- return parseISO(effectiveValue);
+ return plainDateFromISO(effectiveValue);
} else {
- return parseISO(effectiveValue.start);
+ return plainDateFromISO(effectiveValue.start);
}
}
- return new Date();
+ return plainDateToday();
});
// Use controlled focusDate if callback is provided, otherwise use internal state
const isControlledFocus =
focusDateProp !== undefined && onFocusDateChange !== undefined;
const focusDate = isControlledFocus
- ? parseISO(focusDateProp)
+ ? plainDateFromISO(focusDateProp)
: internalFocusDate;
// Expose imperative handle for external navigation
@@ -254,7 +248,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
if (isControlledFocus) {
onFocusDateChange?.(date);
} else {
- setInternalFocusDate(parseISO(date));
+ setInternalFocusDate(plainDateFromISO(date));
}
},
}),
@@ -263,30 +257,24 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
// Base month (first day of focus month)
const baseMonth = useMemo(() => {
- const d = new Date(focusDate);
- d.setDate(1);
- return d;
+ return plainDateSetFirstOfMonth(focusDate);
}, [focusDate]);
// Generate visible months
const visibleMonths = useMemo(() => {
return Array.from({length: numberOfMonths}, (_, i) => {
- const m = new Date(baseMonth);
- m.setMonth(baseMonth.getMonth() + i);
- return m;
+ return plainDateAddMonths(baseMonth, i);
});
}, [baseMonth, numberOfMonths]);
// Format month header
const monthYearLabel = useMemo(() => {
- const formatter = new Intl.DateTimeFormat(undefined, {
- year: 'numeric',
- month: 'long',
- });
if (numberOfMonths === 1) {
- return formatter.format(visibleMonths[0]);
+ return plainDateFormat(visibleMonths[0], DATE_FORMAT_MONTH_YEAR);
}
- return visibleMonths.map(m => formatter.format(m)).join(' – ');
+ return visibleMonths
+ .map(m => plainDateFormat(m, DATE_FORMAT_MONTH_YEAR))
+ .join(' – ');
}, [visibleMonths, numberOfMonths]);
// Determine if prev/next navigation is possible based on min/max
@@ -294,12 +282,11 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
if (!min) {
return true;
}
- const minDate = parseISO(min);
+ const minDate = plainDateFromISO(min);
// Can't go back if min is in the current focus month
return (
- minDate.getFullYear() < baseMonth.getFullYear() ||
- (minDate.getFullYear() === baseMonth.getFullYear() &&
- minDate.getMonth() < baseMonth.getMonth())
+ minDate.year < baseMonth.year ||
+ (minDate.year === baseMonth.year && minDate.month < baseMonth.month)
);
}, [min, baseMonth]);
@@ -307,36 +294,34 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
if (!max) {
return true;
}
- const maxDate = parseISO(max);
+ const maxDate = plainDateFromISO(max);
// Check against the last visible month, not just baseMonth
- const lastVisibleMonth = new Date(baseMonth);
- lastVisibleMonth.setMonth(baseMonth.getMonth() + numberOfMonths - 1);
+ const lastVisibleMonth = plainDateAddMonths(baseMonth, numberOfMonths - 1);
return (
- maxDate.getFullYear() > lastVisibleMonth.getFullYear() ||
- (maxDate.getFullYear() === lastVisibleMonth.getFullYear() &&
- maxDate.getMonth() > lastVisibleMonth.getMonth())
+ maxDate.year > lastVisibleMonth.year ||
+ (maxDate.year === lastVisibleMonth.year &&
+ maxDate.month > lastVisibleMonth.month)
);
}, [max, baseMonth, numberOfMonths]);
// Navigation handlers
const navigateMonth = useCallback(
(delta: number, focusedDate?: ISODateString, offset?: number) => {
- const newDate = new Date(baseMonth);
- newDate.setMonth(baseMonth.getMonth() + delta);
- const newISO = dateToISO(newDate);
+ const newPd = plainDateAddMonths(baseMonth, delta);
+ const newISO = plainDateToISO(newPd);
// Calculate target focus date if a focused date was provided
if (focusedDate) {
- const currentDate = parseISO(focusedDate);
+ const currentPd = plainDateFromISO(focusedDate);
const daysToMove = offset ?? 7;
- currentDate.setDate(currentDate.getDate() + delta * daysToMove);
- setPendingFocus(dateToISO(currentDate));
+ const targetPd = plainDateAddDays(currentPd, delta * daysToMove);
+ setPendingFocus(plainDateToISO(targetPd));
}
if (onFocusDateChange) {
onFocusDateChange(newISO);
} else {
- setInternalFocusDate(newDate);
+ setInternalFocusDate(newPd);
}
},
[baseMonth, onFocusDateChange],
@@ -360,12 +345,15 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
// Day click handler
const handleDayClick = useCallback(
- (date: Date) => {
- const iso = dateToISO(date);
+ (date: PlainDate) => {
+ const iso = plainDateToISO(date);
if (mode === 'single') {
setInternalValue(iso);
- (onChange as XDSCalendarSingleProps['onChange'])?.(iso, date);
+ (onChange as XDSCalendarSingleProps['onChange'])?.(
+ iso,
+ plainDateToDate(date),
+ );
} else {
// Range mode
if (rangeSelectionStart === null) {
@@ -373,12 +361,12 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
setRangeSelectionStart(iso);
} else {
// Second click - complete the range
- const startDate = parseISO(rangeSelectionStart);
+ const startPd = plainDateFromISO(rangeSelectionStart);
let start: ISODateString;
let end: ISODateString;
// Ensure start <= end
- if (date < startDate) {
+ if (plainDateIsBefore(date, startPd)) {
start = iso;
end = rangeSelectionStart;
} else {
@@ -434,7 +422,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
<div {...stylex.props(calendarStyles.monthsContainer)}>
{visibleMonths.map(month => (
<MonthGrid
- key={`${month.getFullYear()}-${month.getMonth()}`}
+ key={`${month.year}-${month.month}`}
month={month}
value={effectiveValue}
mode={mode}
@@ -448,7 +436,9 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
hasVariableRowCount={hasVariableRowCount}
weekStartsOn={weekStartsOn}
onDayClick={handleDayClick}
- onDayHover={date => setHoveredDate(date ? dateToISO(date) : null)}
+ onDayHover={date =>
+ setHoveredDate(date ? plainDateToISO(date) : null)
+ }
today={today}
onNavigatePrevious={(focusedDate, offset) =>
navigateMonth(-1, focusedDate, offset)
@@ -472,7 +462,7 @@ XDSCalendar.displayName = 'XDSCalendar';
// =============================================================================
interface MonthGridProps {
- month: Date;
+ month: PlainDate;
value: ISODateString | DateRange | undefined;
mode: 'single' | 'range';
rangeSelectionStart: ISODateString | null;
@@ -484,9 +474,9 @@ interface MonthGridProps {
hasWeekNumbers: boolean;
hasVariableRowCount: boolean;
weekStartsOn: DayOfWeek;
- onDayClick: (date: Date) => void;
- onDayHover: (date: Date | null) => void;
- today: Date;
+ onDayClick: (date: PlainDate) => void;
+ onDayHover: (date: PlainDate | null) => void;
+ today: PlainDate;
onNavigatePrevious?: (focusedDate: ISODateString, offset: number) => void;
onNavigateNext?: (focusedDate: ISODateString, offset: number) => void;
pendingFocus?: ISODateString | null;
@@ -514,13 +504,12 @@ function MonthGrid({
pendingFocus,
onPendingFocusHandled,
}: MonthGridProps) {
- const year = month.getFullYear();
- const monthIndex = month.getMonth();
+ const year = month.year;
// Use hooks for days generation and constraints
const {days, weeks, dayNames} = useCalendarDays({
year,
- month: monthIndex,
+ month: month.month,
weekStartsOn,
hasVariableRowCount,
});
@@ -534,7 +523,7 @@ function MonthGrid({
// Parse selected date for roving tabindex priority
const selectedDateForTabindex = useMemo(() => {
if (mode === 'single' && value && typeof value === 'string') {
- return parseISO(value as ISODateString);
+ return plainDateFromISO(value as ISODateString);
}
return null;
}, [mode, value]);
@@ -543,7 +532,7 @@ function MonthGrid({
days,
today,
year,
- month: monthIndex,
+ month: month.month,
isDateDisabled,
selectedDate: selectedDateForTabindex,
});
@@ -565,7 +554,7 @@ function MonthGrid({
return null;
}
- return dateToISO(parsed);
+ return plainDateToISO(plainDateFromDate(parsed));
}, []);
// Handle navigation to previous month
@@ -625,8 +614,8 @@ function MonthGrid({
'button:not([disabled])',
);
- const targetDate = parseISO(pendingFocus);
- const targetLabel = formatAccessibleDate(targetDate);
+ const targetPd = plainDateFromISO(pendingFocus);
+ const targetLabel = plainDateFormat(targetPd, DATE_FORMAT_WITH_WEEKDAY);
let targetButton: HTMLElement | null = null;
for (const button of buttons) {
@@ -645,47 +634,44 @@ function MonthGrid({
}, [pendingFocus, gridRef, onPendingFocusHandled]);
// Parse selection
- let selectedDate: Date | null = null;
- let rangeStart: Date | null = null;
- let rangeEnd: Date | null = null;
+ let selectedDate: PlainDate | null = null;
+ let rangeStart: PlainDate | null = null;
+ let rangeEnd: PlainDate | null = null;
if (mode === 'single' && value && typeof value === 'string') {
- selectedDate = parseISO(value as ISODateString);
+ selectedDate = plainDateFromISO(value as ISODateString);
} else if (mode === 'range' && value && typeof value === 'object') {
const range = value as DateRange;
- rangeStart = parseISO(range.start);
- rangeEnd = parseISO(range.end);
+ rangeStart = plainDateFromISO(range.start);
+ rangeEnd = plainDateFromISO(range.end);
}
// Handle in-progress range selection
if (rangeSelectionStart) {
- rangeStart = parseISO(rangeSelectionStart);
+ rangeStart = plainDateFromISO(rangeSelectionStart);
rangeEnd = rangeStart;
}
// Calculate preview range when hovering during range selection
- let previewStart: Date | null = null;
- let previewEnd: Date | null = null;
+ let previewStart: PlainDate | null = null;
+ let previewEnd: PlainDate | null = null;
if (mode === 'range' && rangeSelectionStart && hoveredDate) {
- const startDate = parseISO(rangeSelectionStart);
- const hoverDate = parseISO(hoveredDate);
- if (startDate.getTime() !== hoverDate.getTime()) {
- if (hoverDate < startDate) {
- previewStart = hoverDate;
- previewEnd = startDate;
+ const startPd = plainDateFromISO(rangeSelectionStart);
+ const hoverPd = plainDateFromISO(hoveredDate);
+ if (!plainDateIsEqual(startPd, hoverPd)) {
+ if (plainDateIsBefore(hoverPd, startPd)) {
+ previewStart = hoverPd;
+ previewEnd = startPd;
} else {
- previewStart = startDate;
- previewEnd = hoverDate;
+ previewStart = startPd;
+ previewEnd = hoverPd;
}
}
}
// Month label for announcements
const monthLabel = useMemo(() => {
- return new Intl.DateTimeFormat(undefined, {
- year: 'numeric',
- month: 'long',
- }).format(month);
+ return plainDateFormat(month, DATE_FORMAT_MONTH_YEAR);
}, [month]);
return (
@@ -726,7 +712,7 @@ function MonthGrid({
)}>
{weeks.map((week, weekIndex) => {
const weekDate = week.find(d => !d.isOutside)?.date || week[0].date;
- const weekNum = getWeekNumber(weekDate);
+ const weekNum = plainDateGetWeekNumber(weekDate);
return (
<div
@@ -773,17 +759,17 @@ interface DayCellProps {
day: CalendarDay;
dayIndex: number;
mode: 'single' | 'range';
- selectedDate: Date | null;
- rangeStart: Date | null;
- rangeEnd: Date | null;
- previewStart: Date | null;
- previewEnd: Date | null;
- today: Date;
+ selectedDate: PlainDate | null;
+ rangeStart: PlainDate | null;
+ rangeEnd: PlainDate | null;
+ previewStart: PlainDate | null;
+ previewEnd: PlainDate | null;
+ today: PlainDate;
hasOutsideDays: boolean;
isDisabled: boolean;
isTabbable: boolean;
- onDayClick: (date: Date) => void;
- onDayHover: (date: Date | null) => void;
+ onDayClick: (date: PlainDate) => void;
+ onDayHover: (date: PlainDate | null) => void;
}
function DayCell({
@@ -812,23 +798,26 @@ function DayCell({
// Outside days should not be clickable even when visible
const effectivelyDisabled = isDisabled || isOutside;
- const isToday = isSameDay(date, today);
+ const isToday = plainDateIsEqual(date, today);
const isSelected =
- mode === 'single' && selectedDate && isSameDay(date, selectedDate);
+ mode === 'single' && selectedDate && plainDateIsEqual(date, selectedDate);
const isInRange =
mode === 'range' &&
rangeStart &&
rangeEnd &&
- isDateInRange(date, rangeStart, rangeEnd);
+ plainDateIsInRange(date, [rangeStart, rangeEnd]);
const isRangeStart =
- mode === 'range' && rangeStart && isSameDay(date, rangeStart);
- const isRangeEnd = mode === 'range' && rangeEnd && isSameDay(date, rangeEnd);
+ mode === 'range' && rangeStart && plainDateIsEqual(date, rangeStart);
+ const isRangeEnd =
+ mode === 'range' && rangeEnd && plainDateIsEqual(date, rangeEnd);
// Preview range calculations
const isInPreview =
- previewStart && previewEnd && isDateInRange(date, previewStart, previewEnd);
- const isPreviewStart = previewStart && isSameDay(date, previewStart);
- const isPreviewEnd = previewEnd && isSameDay(date, previewEnd);
+ previewStart &&
+ previewEnd &&
+ plainDateIsInRange(date, [previewStart, previewEnd]);
+ const isPreviewStart = previewStart && plainDateIsEqual(date, previewStart);
+ const isPreviewEnd = previewEnd && plainDateIsEqual(date, previewEnd);
// Determine cell background for range
const hasRangeBackground = isInRange;
@@ -882,7 +871,7 @@ function DayCell({
type="button"
role="gridcell"
data-date={day.iso}
- aria-label={formatAccessibleDate(date)}
+ aria-label={plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY)}
aria-selected={isSelected || isInRange || undefined}
aria-disabled={effectivelyDisabled || undefined}
disabled={isDisabled}
diff --git a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
index 64635352de..da04104c3f 100644
--- a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarConstraints.ts
- * @input Uses React useCallback, useMemo
+ * @input Uses React useCallback, useMemo, PlainDate utilities
* @output Exports useCalendarConstraints hook for date validation
* @position Calendar-specific hook; used by XDSCalendar
*
@@ -13,7 +13,14 @@
*/
import {useCallback, useMemo} from 'react';
-import type {ISODateString} from '../XDSCalendar';
+import type {ISODateString} from '../../utils/dateTypes';
+import {
+ type PlainDate,
+ plainDateFromISO,
+ plainDateToDate,
+ plainDateIsBefore,
+ plainDateIsAfter,
+} from '../../utils/plainDate';
/**
* Configuration for date constraints
@@ -34,20 +41,12 @@ export interface UseCalendarConstraintsOptions {
* Return type for useCalendarConstraints hook
*/
export interface UseCalendarConstraintsReturn {
- /** Check if a date is disabled */
- isDateDisabled: (date: Date) => boolean;
+ /** Check if a PlainDate is disabled */
+ isDateDisabled: (date: PlainDate) => boolean;
/** Parsed min date (or null) */
- minDate: Date | null;
+ minDate: PlainDate | null;
/** Parsed max date (or null) */
- maxDate: Date | null;
-}
-
-/**
- * Parse ISO date string to Date object.
- */
-function parseISO(str: ISODateString): Date {
- const [year, month, day] = str.split('-').map(Number);
- return new Date(year, month - 1, day);
+ maxDate: PlainDate | null;
}
/**
@@ -62,12 +61,12 @@ function parseISO(str: ISODateString): Date {
* min: '2026-01-01',
* max: '2026-12-31',
* dateConstraints: [
- * (date) => date.getDay() !== 0, // No Sundays
+ * (date) => date.getDay() !== 0, // No Sundays (receives native Date)
* ],
* });
*
- * // Check if a date can be selected
- * if (isDateDisabled(someDate)) {
+ * // Check if a PlainDate can be selected
+ * if (isDateDisabled({year: 2026, month: 6, day: 15})) {
* console.log('This date is not selectable');
* }
* ```
@@ -78,26 +77,26 @@ export function useCalendarConstraints(
const {min, max, dateConstraints} = options;
// Parse min/max dates
- const minDate = useMemo(() => (min ? parseISO(min) : null), [min]);
- const maxDate = useMemo(() => (max ? parseISO(max) : null), [max]);
+ const minDate = useMemo(() => (min ? plainDateFromISO(min) : null), [min]);
+ const maxDate = useMemo(() => (max ? plainDateFromISO(max) : null), [max]);
// Check if a date is disabled
const isDateDisabled = useCallback(
- (date: Date): boolean => {
+ (date: PlainDate): boolean => {
// Check min bound
- if (minDate && date < minDate) {
+ if (minDate && plainDateIsBefore(date, minDate)) {
return true;
}
// Check max bound
- if (maxDate && date > maxDate) {
+ if (maxDate && plainDateIsAfter(date, maxDate)) {
return true;
}
- // Check custom constraints
+ // Check custom constraints (convert to Date for public API compatibility)
if (dateConstraints) {
for (const constraint of dateConstraints) {
- if (!constraint(date)) {
+ if (!constraint(plainDateToDate(date))) {
return true;
}
}
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.ts
index 6b3cecd73e..c79af430bb 100644
--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarDays.ts
- * @input Uses React useMemo
+ * @input Uses React useMemo, PlainDate utilities
* @output Exports useCalendarDays hook for generating calendar day grids
* @position Calendar-specific hook; used by XDSCalendar
*
@@ -13,14 +13,21 @@
*/
import {useMemo} from 'react';
-import type {DayOfWeek, ISODateString} from '../XDSCalendar';
+import type {DayOfWeek, ISODateString} from '../../utils/dateTypes';
+import {
+ type PlainDate,
+ plainDateToISO,
+ getDaysInMonth,
+ plainDateDayOfWeek,
+ plainDateAddDays,
+} from '../../utils/plainDate';
/**
* Represents a single day in the calendar grid.
*/
export interface CalendarDay {
- /** The date object for this day */
- date: Date;
+ /** The PlainDate for this day */
+ date: PlainDate;
/** ISO date string (YYYY-MM-DD) */
iso: ISODateString;
/** Whether this day is outside the current month */
@@ -35,7 +42,7 @@ export interface CalendarDay {
export interface UseCalendarDaysOptions {
/** The year to generate days for */
year: number;
- /** The month index (0-11) */
+ /** The month (1-based: 1 = January, 12 = December) */
month: number;
/** First day of week (0=Sunday through 6=Saturday) */
weekStartsOn?: DayOfWeek;
@@ -57,16 +64,6 @@ export interface UseCalendarDaysReturn {
totalCells: number;
}
-/**
- * Convert a Date to ISO date string format.
- */
-function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
/**
* Hook for generating calendar day grids.
*
@@ -77,9 +74,10 @@ function dateToISO(date: Date): ISODateString {
* ```
* const {days, weeks, dayNames} = useCalendarDays({
* year: 2026,
- * month: 0, // January
+ * month: 1, // January (1-based)
* weekStartsOn: 0, // Sunday
* });
+ * // days[i].date is a PlainDate { year, month (1-based), day }
* ```
*/
export function useCalendarDays(
@@ -89,23 +87,22 @@ export function useCalendarDays(
// Calculate grid structure
const gridInfo = useMemo(() => {
- const firstDayOfMonth = new Date(year, month, 1);
- const lastDayOfMonth = new Date(year, month + 1, 0);
- const daysInMonth = lastDayOfMonth.getDate();
+ const totalDaysInMonth = getDaysInMonth(year, month);
// Calculate starting offset based on weekStartsOn
- let startingDayOfWeek = firstDayOfMonth.getDay() - weekStartsOn;
+ let startingDayOfWeek =
+ plainDateDayOfWeek({year, month, day: 1}) - weekStartsOn;
if (startingDayOfWeek < 0) {
startingDayOfWeek += 7;
}
// Calculate total cells
- const totalDays = daysInMonth + startingDayOfWeek;
+ const totalDays = totalDaysInMonth + startingDayOfWeek;
const totalRows = hasVariableRowCount ? Math.ceil(totalDays / 7) : 6;
const totalCells = totalRows * 7;
return {
- daysInMonth,
+ daysInMonth: totalDaysInMonth,
startingDayOfWeek,
totalCells,
};
@@ -123,19 +120,26 @@ export function useCalendarDays(
// Generate days array
const days = useMemo(() => {
- const {daysInMonth, startingDayOfWeek, totalCells} = gridInfo;
+ const {
+ daysInMonth: totalDaysInMonth,
+ startingDayOfWeek,
+ totalCells,
+ } = gridInfo;
+ const firstOfMonth: PlainDate = {year, month, day: 1};
const result: CalendarDay[] = [];
for (let i = 0; i < totalCells; i++) {
const dayOffset = i - startingDayOfWeek + 1;
- const date = new Date(year, month, dayOffset);
- const isOutside = dayOffset < 1 || dayOffset > daysInMonth;
+ const isOutside = dayOffset < 1 || dayOffset > totalDaysInMonth;
+ const pd: PlainDate = isOutside
+ ? plainDateAddDays(firstOfMonth, dayOffset - 1)
+ : {year, month, day: dayOffset};
result.push({
- date,
- iso: dateToISO(date),
+ date: pd,
+ iso: plainDateToISO(pd),
isOutside,
- dayNumber: date.getDate(),
+ dayNumber: pd.day,
});
}
diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
index 03d4bab519..d3db1faffb 100644
--- a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarNavigation.ts
- * @input Uses React useState, useMemo, useCallback
+ * @input Uses React useState, useMemo, useCallback, PlainDate utilities
* @output Exports useCalendarNavigation hook for month navigation
* @position Calendar-specific hook; used by XDSCalendar
*
@@ -13,7 +13,18 @@
*/
import {useState, useMemo, useCallback} from 'react';
-import type {ISODateString} from '../XDSCalendar';
+import type {ISODateString} from '../../utils/dateTypes';
+import {
+ type PlainDate,
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateToday,
+ plainDateSetFirstOfMonth,
+ plainDateAddMonths,
+ plainDateAddDays,
+ plainDateFormat,
+ DATE_FORMAT_MONTH_YEAR,
+} from '../../utils/plainDate';
/**
* Configuration for calendar navigation
@@ -33,10 +44,10 @@ export interface UseCalendarNavigationOptions {
* Return type for useCalendarNavigation hook
*/
export interface UseCalendarNavigationReturn {
- /** The base month (first day of the focus month) */
- baseMonth: Date;
- /** Array of visible months to render */
- visibleMonths: Date[];
+ /** The base month (first day of the focus month) as a PlainDate */
+ baseMonth: PlainDate;
+ /** Array of visible months to render as PlainDates */
+ visibleMonths: PlainDate[];
/** Formatted label for the month header */
monthYearLabel: string;
/** Navigate to previous/next month */
@@ -51,24 +62,6 @@ export interface UseCalendarNavigationReturn {
clearPendingFocus: () => void;
}
-/**
- * Convert a Date to ISO date string format.
- */
-function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
-/**
- * Parse ISO date string to Date object.
- */
-function parseISO(str: ISODateString): Date {
- const [year, month, day] = str.split('-').map(Number);
- return new Date(year, month - 1, day);
-}
-
/**
* Hook for managing calendar month navigation.
*
@@ -109,72 +102,65 @@ export function useCalendarNavigation(
// Pending focus target after month navigation
const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
- // Internal focus date state
- const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
+ // Internal focus date state (PlainDate)
+ const [internalFocusDate, setInternalFocusDate] = useState<PlainDate>(() => {
if (focusDateProp) {
- return parseISO(focusDateProp);
+ return plainDateFromISO(focusDateProp);
}
if (initialValue) {
- return parseISO(initialValue);
+ return plainDateFromISO(initialValue);
}
- return new Date();
+ return plainDateToday();
});
// Determine if focus is controlled
const isControlledFocus =
focusDateProp !== undefined && onFocusDateChange !== undefined;
- const focusDate = isControlledFocus
- ? parseISO(focusDateProp)
+ const focusDate: PlainDate = isControlledFocus
+ ? plainDateFromISO(focusDateProp)
: internalFocusDate;
// Base month (first day of focus month)
const baseMonth = useMemo(() => {
- const d = new Date(focusDate);
- d.setDate(1);
- return d;
+ return plainDateSetFirstOfMonth(focusDate);
}, [focusDate]);
// Generate visible months
const visibleMonths = useMemo(() => {
return Array.from({length: numberOfMonths}, (_, i) => {
- const m = new Date(baseMonth);
- m.setMonth(baseMonth.getMonth() + i);
- return m;
+ return plainDateAddMonths(baseMonth, i);
});
}, [baseMonth, numberOfMonths]);
// Format month header
const monthYearLabel = useMemo(() => {
- const formatter = new Intl.DateTimeFormat(undefined, {
- year: 'numeric',
- month: 'long',
- });
if (numberOfMonths === 1) {
- return formatter.format(visibleMonths[0]);
+ return plainDateFormat(visibleMonths[0], DATE_FORMAT_MONTH_YEAR);
}
- return visibleMonths.map(m => formatter.format(m)).join(' – ');
+ return visibleMonths
+ .map(m => plainDateFormat(m, DATE_FORMAT_MONTH_YEAR))
+ .join(' – ');
}, [visibleMonths, numberOfMonths]);
// Navigate to previous/next month
const navigateMonth = useCallback(
(delta: number, focusedDate?: ISODateString, offset?: number) => {
- const newDate = new Date(baseMonth);
- newDate.setMonth(baseMonth.getMonth() + delta);
- const newISO = dateToISO(newDate);
+ const newMonth = plainDateAddMonths(baseMonth, delta);
+ const newISO = plainDateToISO(newMonth);
// Calculate target focus date if provided
if (focusedDate) {
- const currentDate = parseISO(focusedDate);
+ const currentDate = plainDateFromISO(focusedDate);
// Use the provided offset (1 for horizontal, 7 for vertical)
const daysToMove = offset ?? 7;
- currentDate.setDate(currentDate.getDate() + delta * daysToMove);
- setPendingFocus(dateToISO(currentDate));
+ const targetDate = plainDateAddDays(currentDate, delta * daysToMove);
+ setPendingFocus(plainDateToISO(targetDate));
}
if (onFocusDateChange) {
onFocusDateChange(newISO);
} else {
- setInternalFocusDate(newDate);
+ setInternalFocusDate(newMonth);
}
},
[baseMonth, onFocusDateChange],
diff --git a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts
index c7f1c3746b..77f474c244 100644
--- a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarRovingTabindex.ts
- * @input Uses React useMemo
+ * @input Uses React useMemo, PlainDate utilities
* @output Exports useCalendarRovingTabindex hook for accessible grid navigation
* @position Calendar-specific hook; used by XDSCalendar
*
@@ -13,7 +13,8 @@
*/
import {useMemo} from 'react';
-import type {ISODateString} from '../XDSCalendar';
+import type {ISODateString} from '../../utils/dateTypes';
+import {type PlainDate, plainDateToISO} from '../../utils/plainDate';
import type {CalendarDay} from './useCalendarDays';
/**
@@ -22,16 +23,16 @@ import type {CalendarDay} from './useCalendarDays';
export interface UseCalendarRovingTabindexOptions {
/** All days in the grid */
days: CalendarDay[];
- /** Today's date */
- today: Date;
+ /** Today's date as a PlainDate */
+ today: PlainDate;
/** The year being displayed */
year: number;
- /** The month being displayed (0-11) */
+ /** The month being displayed (1-based: 1 = January, 12 = December) */
month: number;
/** Function to check if a date is disabled */
- isDateDisabled: (date: Date) => boolean;
+ isDateDisabled: (date: PlainDate) => boolean;
/** Currently selected date (if any) */
- selectedDate?: Date | null;
+ selectedDate?: PlainDate | null;
}
/**
@@ -44,16 +45,6 @@ export interface UseCalendarRovingTabindexReturn {
isTabbable: (iso: ISODateString) => boolean;
}
-/**
- * Convert a Date to ISO date string format.
- */
-function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
/**
* Hook for managing roving tabindex in calendar grids.
*
@@ -68,9 +59,9 @@ function dateToISO(date: Date): ISODateString {
* ```
* const {tabbableDate, isTabbable} = useCalendarRovingTabindex({
* days,
- * today: new Date(),
+ * today: {year: 2026, month: 1, day: 20},
* year: 2026,
- * month: 0,
+ * month: 1, // January (1-based)
* isDateDisabled,
* });
*
@@ -90,19 +81,17 @@ export function useCalendarRovingTabindex(
// Priority 1: Selected date if visible in this month and enabled
if (selectedDate) {
const isSelectedInMonth =
- selectedDate.getFullYear() === year &&
- selectedDate.getMonth() === month;
+ selectedDate.year === year && selectedDate.month === month;
if (isSelectedInMonth && !isDateDisabled(selectedDate)) {
- return dateToISO(selectedDate);
+ return plainDateToISO(selectedDate);
}
}
// Priority 2: Today if visible in this month and enabled
- const isTodayInMonth =
- today.getFullYear() === year && today.getMonth() === month;
+ const isTodayInMonth = today.year === year && today.month === month;
if (isTodayInMonth && !isDateDisabled(today)) {
- return dateToISO(today);
+ return plainDateToISO(today);
}
// Priority 3: First enabled day in this month
diff --git a/packages/core/src/Calendar/utils.ts b/packages/core/src/Calendar/utils.ts
index 78b0a2646f..92c9c6a0cd 100644
--- a/packages/core/src/Calendar/utils.ts
+++ b/packages/core/src/Calendar/utils.ts
@@ -3,72 +3,26 @@
/**
* @file utils.ts
* @input None
- * @output Exports shared date utility functions for calendar components
+ * @output Re-exports shared date utility functions for calendar components
* @position Shared utilities; used by XDSCalendar, XDSCalendarMonthGrid, XDSCalendarDayCell
- *
- * SYNC: When modified, update this header
*/
-import type {ISODateString} from './XDSCalendar';
+import {plainDateFormat, DATE_FORMAT_WITH_WEEKDAY} from '../utils/plainDate';
-/**
- * Convert a Date to ISO date string format (YYYY-MM-DD).
- */
-export function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
-/**
- * Parse ISO date string (YYYY-MM-DD) to Date object.
- */
-export function parseISO(str: ISODateString): Date {
- const [year, month, day] = str.split('-').map(Number);
- return new Date(year, month - 1, day);
-}
-
-/**
- * Check if two dates are the same day.
- */
-export function isSameDay(a: Date, b: Date): boolean {
- return (
- a.getFullYear() === b.getFullYear() &&
- a.getMonth() === b.getMonth() &&
- a.getDate() === b.getDate()
- );
-}
-
-/**
- * Check if a date is within a range (inclusive).
- */
-export function isDateInRange(date: Date, start: Date, end: Date): boolean {
- const time = date.getTime();
- return time >= start.getTime() && time <= end.getTime();
-}
+export {
+ type PlainDate,
+ plainDateFromISO as parseISO,
+ plainDateToISO as dateToISO,
+ plainDateIsEqual as isSameDay,
+ plainDateIsInRange as isDateInRange,
+ plainDateGetWeekNumber as getWeekNumber,
+} from '../utils/plainDate';
-/**
- * Get ISO week number for a date.
- */
-export function getWeekNumber(date: Date): number {
- const d = new Date(
- Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
- );
- const dayNum = d.getUTCDay() || 7;
- d.setUTCDate(d.getUTCDate() + 4 - dayNum);
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
- return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
-}
+export {plainDateFormat, DATE_FORMAT_WITH_WEEKDAY};
-/**
- * Format a date for accessible screen reader label.
- */
-export function formatAccessibleDate(date: Date): string {
- return new Intl.DateTimeFormat(undefined, {
- weekday: 'long',
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- }).format(date);
+/** @deprecated Use `plainDateFormat(pd, DATE_FORMAT_WITH_WEEKDAY)` instead. */
+export function formatAccessibleDate(
+ ...args: Parameters<typeof plainDateFormat>
+): string {
+ return plainDateFormat(args[0], DATE_FORMAT_WITH_WEEKDAY);
}
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index c5cf170bbf..edcdc6c2b0 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -53,7 +53,13 @@ import {
} from '../Calendar';
import {useCalendarConstraints} from '../Calendar/hooks';
import {useXDSPopover} from '../Popover';
-import {parseDateInput, formatDisplayDate, parseISO} from '../utils';
+import {parseDateInput} from '../utils';
+import {
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateFormat,
+ DATE_FORMAT_LONG,
+} from '../utils/plainDate';
const styles = stylex.create({
iconButton: {
@@ -341,7 +347,7 @@ export function XDSDateInput({
pendingInput !== null
? pendingInput
: optimisticValue && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
- ? formatDisplayDate(optimisticValue)
+ ? plainDateFormat(plainDateFromISO(optimisticValue), DATE_FORMAT_LONG)
: '';
// Check if current input is valid (for styling purposes)
@@ -415,11 +421,16 @@ export function XDSDateInput({
// If the input is valid and passes constraints, update immediately
const parsed = parseDateInput(newValue);
- if (parsed && parsed !== value && !isDateDisabled(parseISO(parsed))) {
- lastFiredValueRef.current = parsed;
- fireChange(parsed);
+ if (
+ parsed &&
+ plainDateToISO(parsed) !== value &&
+ !isDateDisabled(parsed)
+ ) {
+ const parsedISO = plainDateToISO(parsed);
+ lastFiredValueRef.current = parsedISO;
+ fireChange(parsedISO);
// Navigate calendar to show the parsed date's month
- calendarRef.current?.navigateTo(parsed);
+ calendarRef.current?.navigateTo(parsedISO);
}
},
[value, fireChange, isDateDisabled],
@@ -440,9 +451,10 @@ export function XDSDateInput({
}
const parsed = parseDateInput(pendingInput);
- if (parsed && !isDateDisabled(parseISO(parsed))) {
- if (parsed !== value) {
- fireChange(parsed);
+ if (parsed && !isDateDisabled(parsed)) {
+ const parsedISO = plainDateToISO(parsed);
+ if (parsedISO !== value) {
+ fireChange(parsedISO);
}
}
setPendingInput(null);
diff --git a/packages/core/src/DateRangeInput/XDSDateRangeInput.tsx b/packages/core/src/DateRangeInput/XDSDateRangeInput.tsx
index 825537aa6d..ead5e815d5 100644
--- a/packages/core/src/DateRangeInput/XDSDateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/XDSDateRangeInput.tsx
@@ -18,6 +18,13 @@
import {useId, useCallback, useMemo, useOptimistic, useTransition} from 'react';
import * as stylex from '@stylexjs/stylex';
+import {
+ plainDateFromISO,
+ plainDateToday,
+ plainDateFormat,
+ DATE_FORMAT_SHORT,
+ DATE_FORMAT_SHORT_WITH_YEAR,
+} from '../utils/plainDate';
import type {XDSIconName} from '../Icon';
import {
colorVars,
@@ -163,35 +170,17 @@ const sizeStyles = stylex.create({
},
});
-const shortDateFormatter = new Intl.DateTimeFormat(undefined, {
- month: 'short',
- day: 'numeric',
-});
-
-const shortDateWithYearFormatter = new Intl.DateTimeFormat(undefined, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
-});
-
-function parseISO(iso: ISODateString): Date {
- const [year, month, day] = iso.split('-').map(Number);
- return new Date(year, month - 1, day);
-}
-
function formatRangeDisplay(range: DateRange | null): string {
if (!range) {
return '';
}
- const startDate = parseISO(range.start);
- const endDate = parseISO(range.end);
- const currentYear = new Date().getFullYear();
- const sameYear =
- startDate.getFullYear() === endDate.getFullYear() &&
- startDate.getFullYear() === currentYear;
-
- const fmt = sameYear ? shortDateFormatter : shortDateWithYearFormatter;
- return `${fmt.format(startDate)} – ${fmt.format(endDate)}`;
+ const start = plainDateFromISO(range.start);
+ const end = plainDateFromISO(range.end);
+ const currentYear = plainDateToday().year;
+ const sameYear = start.year === end.year && start.year === currentYear;
+
+ const fmt = sameYear ? DATE_FORMAT_SHORT : DATE_FORMAT_SHORT_WITH_YEAR;
+ return `${plainDateFormat(start, fmt)} – ${plainDateFormat(end, fmt)}`;
}
function isRangeEqual(a: DateRange | null, b: DateRange | null): boolean {
diff --git a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
index f4333adc64..2ae34b2b9f 100644
--- a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
@@ -60,8 +60,6 @@ import {useInputContainer} from '../hooks/useInputContainer';
import {
type ISOTimeString,
parseDateInput,
- formatDisplayDate,
- parseISO,
parseTimeInput,
formatDisplayTime12h,
formatDisplayTime24h,
@@ -71,6 +69,12 @@ import {
xdsClassName,
mergeProps,
} from '../utils';
+import {
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateFormat,
+ DATE_FORMAT_LONG,
+} from '../utils/plainDate';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {XDSBaseProps} from '../XDSBaseProps';
@@ -465,7 +469,7 @@ export function XDSDateTimeInput({
datePendingInput !== null
? datePendingInput
: valueParts.date && /^\d{4}-\d{2}-\d{2}$/.test(valueParts.date)
- ? formatDisplayDate(valueParts.date)
+ ? plainDateFormat(plainDateFromISO(valueParts.date), DATE_FORMAT_LONG)
: '';
const isDateInputValid =
@@ -584,12 +588,13 @@ export function XDSDateTimeInput({
const parsed = parseDateInput(text);
if (
parsed &&
- parsed !== valueParts.date &&
- !isDateDisabled(parseISO(parsed))
+ plainDateToISO(parsed) !== valueParts.date &&
+ !isDateDisabled(parsed)
) {
- lastFiredDateRef.current = parsed;
- handleDateChange(parsed, 'input');
- calendarRef.current?.navigateTo(parsed);
+ const parsedISO = plainDateToISO(parsed);
+ lastFiredDateRef.current = parsedISO;
+ handleDateChange(parsedISO, 'input');
+ calendarRef.current?.navigateTo(parsedISO);
}
},
[valueParts.date, isDateDisabled, handleDateChange],
@@ -609,9 +614,10 @@ export function XDSDateTimeInput({
}
const parsed = parseDateInput(datePendingInput);
- if (parsed && !isDateDisabled(parseISO(parsed))) {
- if (parsed !== valueParts.date) {
- handleDateChange(parsed, 'input');
+ if (parsed && !isDateDisabled(parsed)) {
+ const parsedISO = plainDateToISO(parsed);
+ if (parsedISO !== valueParts.date) {
+ handleDateChange(parsedISO, 'input');
}
}
setDatePendingInput(null);
diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
index 72a757f9bf..44571949af 100644
--- a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
@@ -21,7 +21,7 @@ import type {
} from './types';
import type {InternalConfig} from './useInternalConfig';
import type {XDSSearchableItem, XDSSearchSource} from '../Typeahead/types';
-import type {ISODateString} from '../Calendar';
+import type {ISODateString} from '../utils/dateTypes';
import type {ISOTimeString} from '../utils';
// Lazy import to avoid circular deps — these are all from the same package
diff --git a/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx b/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
index 520719cd77..db39373d21 100644
--- a/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
+++ b/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
@@ -30,7 +30,7 @@ import {XDSPopover} from '../../../Popover';
import {XDSTextInput} from '../../../TextInput';
import {XDSNumberInput} from '../../../NumberInput';
import {XDSDateInput} from '../../../DateInput';
-import type {ISODateString} from '../../../Calendar';
+import type {ISODateString} from '../../../utils/dateTypes';
import {XDSTimeInput} from '../../../TimeInput';
import type {ISOTimeString} from '../../../utils/timeParser';
import {XDSSelector} from '../../../Selector';
diff --git a/packages/core/src/utils/dateParser.test.ts b/packages/core/src/utils/dateParser.test.ts
index cb1d2512b4..29324f3857 100644
--- a/packages/core/src/utils/dateParser.test.ts
+++ b/packages/core/src/utils/dateParser.test.ts
@@ -10,21 +10,24 @@
*/
import {describe, it, expect} from 'vitest';
-import {
- parseDateInput,
- formatDisplayDate,
- dateToISO,
- parseISO,
-} from './dateParser';
+import {parseDateInput} from './dateParser';
describe('parseDateInput', () => {
describe('ISO format (YYYY-MM-DD)', () => {
it('parses valid ISO date', () => {
- expect(parseDateInput('2026-01-25')).toBe('2026-01-25');
+ expect(parseDateInput('2026-01-25')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses ISO date with single-digit month/day', () => {
- expect(parseDateInput('2026-1-5')).toBe('2026-01-05');
+ expect(parseDateInput('2026-1-5')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 5,
+ });
});
it('returns null for invalid ISO date', () => {
@@ -35,48 +38,132 @@ describe('parseDateInput', () => {
describe('full month name formats', () => {
it('parses "January 25, 2026"', () => {
- expect(parseDateInput('January 25, 2026')).toBe('2026-01-25');
+ expect(parseDateInput('January 25, 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses "Jan 25, 2026"', () => {
- expect(parseDateInput('Jan 25, 2026')).toBe('2026-01-25');
+ expect(parseDateInput('Jan 25, 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses "25 January 2026"', () => {
- expect(parseDateInput('25 January 2026')).toBe('2026-01-25');
+ expect(parseDateInput('25 January 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses "25 Jan 2026"', () => {
- expect(parseDateInput('25 Jan 2026')).toBe('2026-01-25');
+ expect(parseDateInput('25 Jan 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses without comma', () => {
- expect(parseDateInput('January 25 2026')).toBe('2026-01-25');
+ expect(parseDateInput('January 25 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('handles case insensitive month names', () => {
- expect(parseDateInput('JANUARY 25, 2026')).toBe('2026-01-25');
- expect(parseDateInput('january 25, 2026')).toBe('2026-01-25');
+ expect(parseDateInput('JANUARY 25, 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
+ expect(parseDateInput('january 25, 2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('parses all month names', () => {
- expect(parseDateInput('February 1, 2026')).toBe('2026-02-01');
- expect(parseDateInput('March 1, 2026')).toBe('2026-03-01');
- expect(parseDateInput('April 1, 2026')).toBe('2026-04-01');
- expect(parseDateInput('May 1, 2026')).toBe('2026-05-01');
- expect(parseDateInput('June 1, 2026')).toBe('2026-06-01');
- expect(parseDateInput('July 1, 2026')).toBe('2026-07-01');
- expect(parseDateInput('August 1, 2026')).toBe('2026-08-01');
- expect(parseDateInput('September 1, 2026')).toBe('2026-09-01');
- expect(parseDateInput('October 1, 2026')).toBe('2026-10-01');
- expect(parseDateInput('November 1, 2026')).toBe('2026-11-01');
- expect(parseDateInput('December 1, 2026')).toBe('2026-12-01');
+ expect(parseDateInput('February 1, 2026')).toEqual({
+ year: 2026,
+ month: 2,
+ day: 1,
+ });
+ expect(parseDateInput('March 1, 2026')).toEqual({
+ year: 2026,
+ month: 3,
+ day: 1,
+ });
+ expect(parseDateInput('April 1, 2026')).toEqual({
+ year: 2026,
+ month: 4,
+ day: 1,
+ });
+ expect(parseDateInput('May 1, 2026')).toEqual({
+ year: 2026,
+ month: 5,
+ day: 1,
+ });
+ expect(parseDateInput('June 1, 2026')).toEqual({
+ year: 2026,
+ month: 6,
+ day: 1,
+ });
+ expect(parseDateInput('July 1, 2026')).toEqual({
+ year: 2026,
+ month: 7,
+ day: 1,
+ });
+ expect(parseDateInput('August 1, 2026')).toEqual({
+ year: 2026,
+ month: 8,
+ day: 1,
+ });
+ expect(parseDateInput('September 1, 2026')).toEqual({
+ year: 2026,
+ month: 9,
+ day: 1,
+ });
+ expect(parseDateInput('October 1, 2026')).toEqual({
+ year: 2026,
+ month: 10,
+ day: 1,
+ });
+ expect(parseDateInput('November 1, 2026')).toEqual({
+ year: 2026,
+ month: 11,
+ day: 1,
+ });
+ expect(parseDateInput('December 1, 2026')).toEqual({
+ year: 2026,
+ month: 12,
+ day: 1,
+ });
});
it('parses abbreviated month names', () => {
- expect(parseDateInput('Feb 1, 2026')).toBe('2026-02-01');
- expect(parseDateInput('Sep 1, 2026')).toBe('2026-09-01');
- expect(parseDateInput('Sept 1, 2026')).toBe('2026-09-01');
+ expect(parseDateInput('Feb 1, 2026')).toEqual({
+ year: 2026,
+ month: 2,
+ day: 1,
+ });
+ expect(parseDateInput('Sep 1, 2026')).toEqual({
+ year: 2026,
+ month: 9,
+ day: 1,
+ });
+ expect(parseDateInput('Sept 1, 2026')).toEqual({
+ year: 2026,
+ month: 9,
+ day: 1,
+ });
});
});
@@ -84,48 +171,100 @@ describe('parseDateInput', () => {
const currentYear = new Date().getFullYear();
it('parses "January 25" (month-first without year)', () => {
- expect(parseDateInput('January 25')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('January 25')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "Jan 25" (abbreviated month without year)', () => {
- expect(parseDateInput('Jan 25')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('Jan 25')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "25 January" (day-first without year)', () => {
- expect(parseDateInput('25 January')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('25 January')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "25 Jan" (day-first abbreviated without year)', () => {
- expect(parseDateInput('25 Jan')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('25 Jan')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "1/25" (numeric without year)', () => {
- expect(parseDateInput('1/25')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('1/25')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "25/1" (numeric day-first without year)', () => {
- expect(parseDateInput('25/1')).toBe(`${currentYear}-01-25`);
+ expect(parseDateInput('25/1')).toEqual({
+ year: currentYear,
+ month: 1,
+ day: 25,
+ });
});
it('parses "12-31" (numeric with dash without year)', () => {
- expect(parseDateInput('12-31')).toBe(`${currentYear}-12-31`);
+ expect(parseDateInput('12-31')).toEqual({
+ year: currentYear,
+ month: 12,
+ day: 31,
+ });
});
it('handles all months without year', () => {
- expect(parseDateInput('Feb 15')).toBe(`${currentYear}-02-15`);
- expect(parseDateInput('Dec 25')).toBe(`${currentYear}-12-25`);
+ expect(parseDateInput('Feb 15')).toEqual({
+ year: currentYear,
+ month: 2,
+ day: 15,
+ });
+ expect(parseDateInput('Dec 25')).toEqual({
+ year: currentYear,
+ month: 12,
+ day: 25,
+ });
});
});
describe('numeric formats with heuristics', () => {
it('detects day when first number > 12', () => {
- expect(parseDateInput('25/1/2026')).toBe('2026-01-25');
- expect(parseDateInput('31-12-2026')).toBe('2026-12-31');
+ expect(parseDateInput('25/1/2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
+ expect(parseDateInput('31-12-2026')).toEqual({
+ year: 2026,
+ month: 12,
+ day: 31,
+ });
});
it('detects day when second number > 12', () => {
- expect(parseDateInput('1/25/2026')).toBe('2026-01-25');
- expect(parseDateInput('12-31-2026')).toBe('2026-12-31');
+ expect(parseDateInput('1/25/2026')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
+ expect(parseDateInput('12-31-2026')).toEqual({
+ year: 2026,
+ month: 12,
+ day: 31,
+ });
});
it('returns null when both numbers > 12', () => {
@@ -148,7 +287,11 @@ describe('parseDateInput', () => {
});
it('trims whitespace', () => {
- expect(parseDateInput(' 2026-01-25 ')).toBe('2026-01-25');
+ expect(parseDateInput(' 2026-01-25 ')).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
});
it('returns null for completely invalid strings', () => {
@@ -157,13 +300,21 @@ describe('parseDateInput', () => {
});
it('validates February dates', () => {
- expect(parseDateInput('February 29, 2024')).toBe('2024-02-29'); // Leap year
+ expect(parseDateInput('February 29, 2024')).toEqual({
+ year: 2024,
+ month: 2,
+ day: 29,
+ }); // Leap year
expect(parseDateInput('February 29, 2025')).toBeNull(); // Not a leap year
expect(parseDateInput('February 30, 2024')).toBeNull();
});
it('preserves years 0-99 literally instead of mapping to 1900s', () => {
- expect(parseDateInput('01/01/0050')).toBe('0050-01-01');
+ expect(parseDateInput('01/01/0050')).toEqual({
+ year: 50,
+ month: 1,
+ day: 1,
+ });
});
it('rejects mixed separators', () => {
@@ -171,39 +322,3 @@ describe('parseDateInput', () => {
});
});
});
-
-describe('formatDisplayDate', () => {
- it('formats ISO date to readable format', () => {
- expect(formatDisplayDate('2026-01-25')).toBe('January 25, 2026');
- });
-
- it('formats single-digit dates correctly', () => {
- expect(formatDisplayDate('2026-01-05')).toBe('January 5, 2026');
- });
-
- it('formats all months correctly', () => {
- expect(formatDisplayDate('2026-02-15')).toBe('February 15, 2026');
- expect(formatDisplayDate('2026-12-25')).toBe('December 25, 2026');
- });
-});
-
-describe('dateToISO', () => {
- it('converts Date object to ISO string', () => {
- const date = new Date(2026, 0, 25); // January 25, 2026
- expect(dateToISO(date)).toBe('2026-01-25');
- });
-
- it('pads single-digit month and day', () => {
- const date = new Date(2026, 0, 5); // January 5, 2026
- expect(dateToISO(date)).toBe('2026-01-05');
- });
-});
-
-describe('parseISO', () => {
- it('parses ISO string to Date object', () => {
- const date = parseISO('2026-01-25');
- expect(date.getFullYear()).toBe(2026);
- expect(date.getMonth()).toBe(0); // January
- expect(date.getDate()).toBe(25);
- });
-});
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
index 7bb0d047de..30f04ac2be 100644
--- a/packages/core/src/utils/dateParser.ts
+++ b/packages/core/src/utils/dateParser.ts
@@ -4,14 +4,19 @@
* @file dateParser.ts
* @input Uses Intl.DateTimeFormat for locale detection
* @output Exports date parsing utilities for user input
- * @position Core utility; used by XDSDatePicker
+ * @position Core utility; used by XDSDateInput, XDSDateTimeInput
*
* SYNC: When modified, update:
* - /packages/core/src/utils/dateParser.test.ts
* - /packages/core/src/utils/index.ts
*/
-import type {ISODateString} from '../Calendar';
+import {type PlainDate, plainDateCreate, plainDateFromDate} from './plainDate';
+
+export {
+ plainDateFromISO as parseISO,
+ plainDateToISO as dateToISO,
+} from './plainDate';
/**
* Detects if the user's locale uses day-first date format (DD/MM/YYYY).
@@ -25,7 +30,7 @@ export function isLocaleDayFirst(): boolean {
}
/**
- * Parses user input into an ISO date string.
+ * Parses user input into a PlainDate.
*
* Supports:
* - ISO format: "2026-01-25"
@@ -36,9 +41,9 @@ export function isLocaleDayFirst(): boolean {
*
* For ambiguous numeric formats (both numbers ≤ 12), uses locale preference.
*
- * @returns ISODateString if valid, null if unparseable
+ * @returns PlainDate if valid, null if unparseable
*/
-export function parseDateInput(input: string): ISODateString | null {
+export function parseDateInput(input: string): PlainDate | null {
const trimmed = input.trim();
if (!trimmed) {
return null;
@@ -50,7 +55,7 @@ export function parseDateInput(input: string): ISODateString | null {
const isoMatch = trimmed.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
if (isoMatch) {
const [, year, month, day] = isoMatch;
- return createISODate(+year, +month, +day);
+ return tryCreatePlainDate(+year, +month, +day);
}
// 2. Try full month name formats with year
@@ -62,7 +67,7 @@ export function parseDateInput(input: string): ISODateString | null {
const [, monthName, day, year] = monthFirstWithYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
- return createISODate(+year, month, +day);
+ return tryCreatePlainDate(+year, month, +day);
}
}
@@ -74,7 +79,7 @@ export function parseDateInput(input: string): ISODateString | null {
const [, day, monthName, year] = dayFirstWithYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
- return createISODate(+year, month, +day);
+ return tryCreatePlainDate(+year, month, +day);
}
}
@@ -85,7 +90,7 @@ export function parseDateInput(input: string): ISODateString | null {
const [, monthName, day] = monthFirstNoYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
- return createISODate(currentYear, month, +day);
+ return tryCreatePlainDate(currentYear, month, +day);
}
}
@@ -95,7 +100,7 @@ export function parseDateInput(input: string): ISODateString | null {
const [, day, monthName] = dayFirstNoYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
- return createISODate(currentYear, month, +day);
+ return tryCreatePlainDate(currentYear, month, +day);
}
}
@@ -105,7 +110,7 @@ export function parseDateInput(input: string): ISODateString | null {
);
if (numericWithYearMatch) {
const [, first, sep1, second, sep2, year] = numericWithYearMatch;
- // Reject mixed separators (e.g., "1/25.2026")
+
if (sep1 !== sep2) {
return null;
}
@@ -122,41 +127,29 @@ export function parseDateInput(input: string): ISODateString | null {
// 6. Fall back to native Date parsing for other formats
const parsed = new Date(trimmed);
if (!isNaN(parsed.getTime())) {
- return dateToISO(parsed);
+ return plainDateFromDate(parsed);
}
return null;
}
-/**
- * Parses ambiguous numeric dates using heuristics and locale.
- *
- * Heuristics:
- * - If first > 12, it must be the day (e.g., 25/1/2026 → Jan 25)
- * - If second > 12, it must be the day (e.g., 1/25/2026 → Jan 25)
- * - If both ≤ 12, use locale preference (day-first vs month-first)
- */
function parseNumericDate(
first: number,
second: number,
year: number,
-): ISODateString | null {
+): PlainDate | null {
let day: number;
let month: number;
if (first > 12 && second <= 12) {
- // First must be day (e.g., 25/1/2026)
day = first;
month = second;
} else if (second > 12 && first <= 12) {
- // Second must be day (e.g., 1/25/2026)
month = first;
day = second;
} else if (first > 12 && second > 12) {
- // Both > 12 is invalid
return null;
} else {
- // Both ≤ 12: ambiguous, use locale preference
if (isLocaleDayFirst()) {
day = first;
month = second;
@@ -166,12 +159,9 @@ function parseNumericDate(
}
}
- return createISODate(year, month, day);
+ return tryCreatePlainDate(year, month, day);
}
-/**
- * Parses month name (full or abbreviated) to 1-12.
- */
function parseMonthName(name: string): number | null {
const months: Record<string, number> = {
january: 1,
@@ -202,66 +192,14 @@ function parseMonthName(name: string): number | null {
return months[name.toLowerCase()] ?? null;
}
-/**
- * Creates an ISO date string, validating the date is real.
- */
-function createISODate(
+function tryCreatePlainDate(
year: number,
month: number,
day: number,
-): ISODateString | null {
- if (month < 1 || month > 12 || day < 1 || day > 31) {
+): PlainDate | null {
+ try {
+ return plainDateCreate(year, month, day);
+ } catch {
return null;
}
-
- const date = new Date(year, month - 1, day);
- // new Date(year, ...) treats 0-99 as 1900s; fix with setFullYear
- date.setFullYear(year);
-
- // Validate the date didn't overflow (e.g., Feb 30 → Mar 2)
- if (
- date.getFullYear() !== year ||
- date.getMonth() !== month - 1 ||
- date.getDate() !== day
- ) {
- return null;
- }
-
- return dateToISO(date);
-}
-
-/**
- * Converts a Date object to ISO date string.
- */
-export function dateToISO(date: Date): ISODateString {
- const year = String(date.getFullYear()).padStart(4, '0');
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
-/**
- * Parses an ISO date string into a Date object.
- */
-export function parseISO(iso: ISODateString): Date {
- const [year, month, day] = iso.split('-').map(Number);
- return new Date(year, month - 1, day);
-}
-
-/**
- * Formats an ISO date string for display.
- * Uses locale-aware formatting with full month name.
- *
- * @example
- * ```
- * formatDisplayDate("2026-01-25") // "January 25, 2026"
- * ```
- */
-export function formatDisplayDate(iso: ISODateString): string {
- const date = parseISO(iso);
- return new Intl.DateTimeFormat(undefined, {
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- }).format(date);
}
diff --git a/packages/core/src/utils/dateTypes.ts b/packages/core/src/utils/dateTypes.ts
new file mode 100644
index 0000000000..b9879f04ac
--- /dev/null
+++ b/packages/core/src/utils/dateTypes.ts
@@ -0,0 +1,32 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file dateTypes.ts
+ * @input None
+ * @output Shared date type definitions used across Calendar, DateInput, and other components
+ * @position Core type definitions; imported by Calendar, DateInput, DateRangeInput, DateTimeInput, plainDate, dateParser
+ */
+
+/**
+ * ISO 8601 date string in YYYY-MM-DD format.
+ * Example: "2026-01-28"
+ */
+export type ISODateString =
+ `${number}${number}${number}${number}-${number}${number}-${number}${number}`;
+
+/** Day of week: 0 = Sunday through 6 = Saturday */
+export type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
+
+/** Immutable date record with 1-based month. */
+export interface PlainDate {
+ readonly year: number;
+ /** 1-based (1 = January, 12 = December) */
+ readonly month: number;
+ readonly day: number;
+}
+
+/** Date range with start and end dates */
+export interface DateRange {
+ start: ISODateString;
+ end: ISODateString;
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 3f7409b906..900dd34dda 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -9,14 +9,40 @@
export type {SizeValue} from './types';
+export type {ISODateString, DayOfWeek, PlainDate, DateRange} from './dateTypes';
+
export {
parseDateInput,
- formatDisplayDate,
dateToISO,
parseISO,
isLocaleDayFirst,
} from './dateParser';
+export {
+ plainDateCreate,
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateToDate,
+ plainDateFromDate,
+ plainDateToday,
+ getDaysInMonth,
+ plainDateDayOfWeek,
+ plainDateAddMonths,
+ plainDateAddDays,
+ plainDateIsBefore,
+ plainDateIsAfter,
+ plainDateIsEqual,
+ plainDateIsInRange,
+ plainDateSetFirstOfMonth,
+ plainDateGetWeekNumber,
+ plainDateFormat,
+ DATE_FORMAT_WITH_WEEKDAY,
+ DATE_FORMAT_LONG,
+ DATE_FORMAT_MONTH_YEAR,
+ DATE_FORMAT_SHORT,
+ DATE_FORMAT_SHORT_WITH_YEAR,
+} from './plainDate';
+
export {
parseISOTime,
formatISOTime,
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
new file mode 100644
index 0000000000..3b04590f4f
--- /dev/null
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -0,0 +1,444 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {
+ type PlainDate,
+ plainDateCreate,
+ plainDateFromISO,
+ plainDateToISO,
+ plainDateToDate,
+ plainDateFromDate,
+ plainDateToday,
+ getDaysInMonth,
+ plainDateDayOfWeek,
+ plainDateAddMonths,
+ plainDateAddDays,
+ plainDateIsBefore,
+ plainDateIsAfter,
+ plainDateIsEqual,
+ plainDateIsInRange,
+ plainDateSetFirstOfMonth,
+ plainDateGetWeekNumber,
+ plainDateFormat,
+ DATE_FORMAT_WITH_WEEKDAY,
+} from './plainDate';
+import type {ISODateString} from './dateTypes';
+
+describe('plainDateCreate', () => {
+ it('creates a valid PlainDate', () => {
+ expect(plainDateCreate(2026, 1, 25)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
+ });
+
+ it('throws for year < 1', () => {
+ expect(() => plainDateCreate(0, 1, 1)).toThrow(RangeError);
+ });
+
+ it('throws for negative year', () => {
+ expect(() => plainDateCreate(-1, 1, 1)).toThrow(RangeError);
+ });
+
+ it('throws for non-integer year', () => {
+ expect(() => plainDateCreate(2026.5, 1, 1)).toThrow(RangeError);
+ });
+
+ it('throws for non-integer month', () => {
+ expect(() => plainDateCreate(2026, 1.5, 1)).toThrow(RangeError);
+ });
+
+ it('throws for non-integer day', () => {
+ expect(() => plainDateCreate(2026, 1, 1.5)).toThrow(RangeError);
+ });
+
+ it('throws for month < 1', () => {
+ expect(() => plainDateCreate(2026, 0, 1)).toThrow(RangeError);
+ });
+
+ it('throws for month > 12', () => {
+ expect(() => plainDateCreate(2026, 13, 1)).toThrow(RangeError);
+ });
+
+ it('throws for day < 1', () => {
+ expect(() => plainDateCreate(2026, 1, 0)).toThrow(RangeError);
+ });
+
+ it('throws for day exceeding month length', () => {
+ expect(() => plainDateCreate(2026, 2, 29)).toThrow(RangeError);
+ });
+
+ it('allows Feb 29 in a leap year', () => {
+ expect(plainDateCreate(2024, 2, 29)).toEqual({
+ year: 2024,
+ month: 2,
+ day: 29,
+ });
+ });
+
+ it('throws for Feb 30 even in a leap year', () => {
+ expect(() => plainDateCreate(2024, 2, 30)).toThrow(RangeError);
+ });
+});
+
+describe('plainDateFromISO', () => {
+ it('parses a standard ISO date', () => {
+ expect(plainDateFromISO('2026-01-25' as ISODateString)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 25,
+ });
+ });
+
+ it('parses date with 1-based month', () => {
+ const dec = plainDateFromISO('2026-12-31' as ISODateString);
+ expect(dec.month).toBe(12);
+ });
+
+ it('handles single-digit month/day when padded', () => {
+ expect(plainDateFromISO('2026-03-05' as ISODateString)).toEqual({
+ year: 2026,
+ month: 3,
+ day: 5,
+ });
+ });
+});
+
+describe('plainDateToISO', () => {
+ it('formats a PlainDate to ISO string', () => {
+ expect(plainDateToISO({year: 2026, month: 1, day: 25})).toBe('2026-01-25');
+ });
+
+ it('pads single-digit month and day', () => {
+ expect(plainDateToISO({year: 2026, month: 3, day: 5})).toBe('2026-03-05');
+ });
+
+ it('pads year to 4 digits', () => {
+ expect(plainDateToISO({year: 1, month: 1, day: 1})).toBe('0001-01-01');
+ });
+});
+
+describe('plainDateFromISO / plainDateToISO roundtrip', () => {
+ it.each([
+ '2026-01-01',
+ '2026-06-15',
+ '2026-12-31',
+ '2000-02-29',
+ '1999-11-30',
+ ])('roundtrips %s', iso => {
+ expect(plainDateToISO(plainDateFromISO(iso as ISODateString))).toBe(iso);
+ });
+});
+
+describe('plainDateToDate / plainDateFromDate', () => {
+ it('converts PlainDate to Date and back', () => {
+ const pd: PlainDate = {year: 2026, month: 3, day: 15};
+ const d = plainDateToDate(pd);
+ expect(d.getFullYear()).toBe(2026);
+ expect(d.getMonth()).toBe(2); // 0-based
+ expect(d.getDate()).toBe(15);
+ expect(plainDateFromDate(d)).toEqual(pd);
+ });
+});
+
+describe('plainDateToday', () => {
+ it('returns current date with 1-based month', () => {
+ const t = plainDateToday();
+ const now = new Date();
+ expect(t.year).toBe(now.getFullYear());
+ expect(t.month).toBe(now.getMonth() + 1);
+ expect(t.day).toBe(now.getDate());
+ });
+});
+
+describe('getDaysInMonth', () => {
+ it('returns 31 for January', () => {
+ expect(getDaysInMonth(2026, 1)).toBe(31);
+ });
+
+ it('returns 28 for February in a non-leap year', () => {
+ expect(getDaysInMonth(2026, 2)).toBe(28);
+ });
+
+ it('returns 29 for February in a leap year', () => {
+ expect(getDaysInMonth(2024, 2)).toBe(29);
+ });
+
+ it('returns 30 for April', () => {
+ expect(getDaysInMonth(2026, 4)).toBe(30);
+ });
+
+ it('handles century non-leap year', () => {
+ expect(getDaysInMonth(1900, 2)).toBe(28);
+ });
+
+ it('handles 400-year leap year', () => {
+ expect(getDaysInMonth(2000, 2)).toBe(29);
+ });
+});
+
+describe('plainDateDayOfWeek', () => {
+ it('returns 0 for a known Sunday', () => {
+ // 2026-01-04 is a Sunday
+ expect(plainDateDayOfWeek({year: 2026, month: 1, day: 4})).toBe(0);
+ });
+
+ it('returns 1 for a known Monday', () => {
+ // 2026-01-05 is a Monday
+ expect(plainDateDayOfWeek({year: 2026, month: 1, day: 5})).toBe(1);
+ });
+
+ it('returns 6 for a known Saturday', () => {
+ // 2026-01-03 is a Saturday
+ expect(plainDateDayOfWeek({year: 2026, month: 1, day: 3})).toBe(6);
+ });
+});
+
+describe('plainDateAddMonths', () => {
+ it('adds months within the same year', () => {
+ expect(plainDateAddMonths({year: 2026, month: 1, day: 15}, 3)).toEqual({
+ year: 2026,
+ month: 4,
+ day: 15,
+ });
+ });
+
+ it('rolls over to the next year', () => {
+ expect(plainDateAddMonths({year: 2026, month: 11, day: 15}, 3)).toEqual({
+ year: 2027,
+ month: 2,
+ day: 15,
+ });
+ });
+
+ it('subtracts months', () => {
+ expect(plainDateAddMonths({year: 2026, month: 3, day: 15}, -2)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 15,
+ });
+ });
+
+ it('rolls back to previous year', () => {
+ expect(plainDateAddMonths({year: 2026, month: 1, day: 15}, -2)).toEqual({
+ year: 2025,
+ month: 11,
+ day: 15,
+ });
+ });
+
+ it('overflows day into next month when target month is shorter', () => {
+ expect(plainDateAddMonths({year: 2026, month: 1, day: 31}, 1)).toEqual({
+ year: 2026,
+ month: 3,
+ day: 3,
+ });
+ });
+
+ it('overflows Jan 31 + 1 month in leap year', () => {
+ expect(plainDateAddMonths({year: 2024, month: 1, day: 31}, 1)).toEqual({
+ year: 2024,
+ month: 3,
+ day: 2,
+ });
+ });
+});
+
+describe('plainDateAddDays', () => {
+ it('adds days within the same month', () => {
+ expect(plainDateAddDays({year: 2026, month: 1, day: 15}, 5)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 20,
+ });
+ });
+
+ it('rolls over to next month', () => {
+ expect(plainDateAddDays({year: 2026, month: 1, day: 30}, 3)).toEqual({
+ year: 2026,
+ month: 2,
+ day: 2,
+ });
+ });
+
+ it('rolls over to next year', () => {
+ expect(plainDateAddDays({year: 2026, month: 12, day: 30}, 3)).toEqual({
+ year: 2027,
+ month: 1,
+ day: 2,
+ });
+ });
+
+ it('subtracts days', () => {
+ expect(plainDateAddDays({year: 2026, month: 1, day: 15}, -5)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 10,
+ });
+ });
+
+ it('rolls back to previous month', () => {
+ expect(plainDateAddDays({year: 2026, month: 2, day: 1}, -1)).toEqual({
+ year: 2026,
+ month: 1,
+ day: 31,
+ });
+ });
+});
+
+describe('plainDateIsBefore / plainDateIsAfter', () => {
+ it('returns false for equal dates (isBefore)', () => {
+ expect(
+ plainDateIsBefore(
+ {year: 2026, month: 1, day: 15},
+ {year: 2026, month: 1, day: 15},
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false for equal dates (isAfter)', () => {
+ expect(
+ plainDateIsAfter(
+ {year: 2026, month: 1, day: 15},
+ {year: 2026, month: 1, day: 15},
+ ),
+ ).toBe(false);
+ });
+
+ it('returns true when first is earlier (isBefore)', () => {
+ expect(
+ plainDateIsBefore(
+ {year: 2026, month: 1, day: 14},
+ {year: 2026, month: 1, day: 15},
+ ),
+ ).toBe(true);
+ });
+
+ it('returns true when first is later (isAfter)', () => {
+ expect(
+ plainDateIsAfter(
+ {year: 2026, month: 1, day: 16},
+ {year: 2026, month: 1, day: 15},
+ ),
+ ).toBe(true);
+ });
+
+ it('compares by year first', () => {
+ expect(
+ plainDateIsBefore(
+ {year: 2025, month: 12, day: 31},
+ {year: 2026, month: 1, day: 1},
+ ),
+ ).toBe(true);
+ });
+
+ it('compares by month when years equal', () => {
+ expect(
+ plainDateIsBefore(
+ {year: 2026, month: 1, day: 31},
+ {year: 2026, month: 2, day: 1},
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('plainDateIsEqual', () => {
+ it('returns true for same date', () => {
+ expect(
+ plainDateIsEqual(
+ {year: 2026, month: 1, day: 15},
+ {year: 2026, month: 1, day: 15},
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false for different day', () => {
+ expect(
+ plainDateIsEqual(
+ {year: 2026, month: 1, day: 15},
+ {year: 2026, month: 1, day: 16},
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false for different month', () => {
+ expect(
+ plainDateIsEqual(
+ {year: 2026, month: 1, day: 15},
+ {year: 2026, month: 2, day: 15},
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('plainDateIsInRange', () => {
+ const start: PlainDate = {year: 2026, month: 1, day: 10};
+ const end: PlainDate = {year: 2026, month: 1, day: 20};
+
+ it('returns true for date within range', () => {
+ expect(
+ plainDateIsInRange({year: 2026, month: 1, day: 15}, [start, end]),
+ ).toBe(true);
+ });
+
+ it('returns true for start boundary', () => {
+ expect(plainDateIsInRange(start, [start, end])).toBe(true);
+ });
+
+ it('returns true for end boundary', () => {
+ expect(plainDateIsInRange(end, [start, end])).toBe(true);
+ });
+
+ it('returns false for date before range', () => {
+ expect(
+ plainDateIsInRange({year: 2026, month: 1, day: 9}, [start, end]),
+ ).toBe(false);
+ });
+
+ it('returns false for date after range', () => {
+ expect(
+ plainDateIsInRange({year: 2026, month: 1, day: 21}, [start, end]),
+ ).toBe(false);
+ });
+});
+
+describe('plainDateSetFirstOfMonth', () => {
+ it('returns first day of the same month', () => {
+ expect(plainDateSetFirstOfMonth({year: 2026, month: 3, day: 15})).toEqual({
+ year: 2026,
+ month: 3,
+ day: 1,
+ });
+ });
+
+ it('is a no-op for day 1', () => {
+ const pd = {year: 2026, month: 3, day: 1};
+ expect(plainDateSetFirstOfMonth(pd)).toEqual(pd);
+ });
+});
+
+describe('plainDateGetWeekNumber', () => {
+ it('returns week 1 for Jan 1 2026 (Thursday)', () => {
+ expect(plainDateGetWeekNumber({year: 2026, month: 1, day: 1})).toBe(1);
+ });
+
+ it('returns week 53 for Dec 31 2020 (Thursday in ISO week 53)', () => {
+ expect(plainDateGetWeekNumber({year: 2020, month: 12, day: 31})).toBe(53);
+ });
+
+ it('returns week 1 for Jan 4 (always in ISO week 1)', () => {
+ expect(plainDateGetWeekNumber({year: 2026, month: 1, day: 4})).toBe(1);
+ });
+});
+
+describe('plainDateFormat', () => {
+ it('returns a human-readable date string with weekday', () => {
+ const result = plainDateFormat(
+ {year: 2026, month: 1, day: 25},
+ DATE_FORMAT_WITH_WEEKDAY,
+ );
+ expect(result).toContain('2026');
+ expect(result).toContain('25');
+ });
+});
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
new file mode 100644
index 0000000000..0b827682cd
--- /dev/null
+++ b/packages/core/src/utils/plainDate.ts
@@ -0,0 +1,168 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file plainDate.ts
+ * @input ISO date strings, year/month/day numbers
+ * @output Immutable PlainDate records and pure date arithmetic
+ * @position Shared utility; replaces scattered Date usage across Calendar hooks
+ */
+
+import type {ISODateString, PlainDate} from './dateTypes';
+
+export type {PlainDate} from './dateTypes';
+
+export function plainDateCreate(
+ year: number,
+ month: number,
+ day: number,
+): PlainDate {
+ if (!Number.isInteger(year) || year < 1) {
+ throw new RangeError(`year must be a positive integer, got ${year}`);
+ }
+ if (!Number.isInteger(month) || month < 1 || month > 12) {
+ throw new RangeError(`month must be 1–12, got ${month}`);
+ }
+ const maxDay = getDaysInMonth(year, month);
+ if (!Number.isInteger(day) || day < 1 || day > maxDay) {
+ throw new RangeError(
+ `day must be 1–${maxDay} for ${year}-${String(month).padStart(2, '0')}, got ${day}`,
+ );
+ }
+ return {year, month, day};
+}
+
+export function plainDateFromISO(str: ISODateString): PlainDate {
+ const [year, month, day] = str.split('-').map(Number);
+ return plainDateCreate(year, month, day);
+}
+
+export function plainDateToISO(pd: PlainDate): ISODateString {
+ const y = String(pd.year).padStart(4, '0');
+ const m = String(pd.month).padStart(2, '0');
+ const d = String(pd.day).padStart(2, '0');
+ return `${y}-${m}-${d}` as ISODateString;
+}
+
+export function plainDateToDate(pd: PlainDate): Date {
+ return new Date(pd.year, pd.month - 1, pd.day);
+}
+
+export function plainDateFromDate(d: Date): PlainDate {
+ return {
+ year: d.getFullYear(),
+ month: d.getMonth() + 1,
+ day: d.getDate(),
+ };
+}
+
+export function plainDateToday(): PlainDate {
+ return plainDateFromDate(new Date());
+}
+
+export function getDaysInMonth(year: number, month: number): number {
+ if (month === 2) {
+ const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+ return isLeap ? 29 : 28;
+ }
+ return [0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
+}
+
+export function plainDateDayOfWeek(pd: PlainDate): number {
+ return plainDateToDate(pd).getDay();
+}
+
+export function plainDateAddMonths(pd: PlainDate, n: number): PlainDate {
+ const d = plainDateToDate(pd);
+ d.setMonth(d.getMonth() + n);
+ return plainDateFromDate(d);
+}
+
+export function plainDateAddDays(pd: PlainDate, n: number): PlainDate {
+ const d = plainDateToDate(pd);
+ d.setDate(d.getDate() + n);
+ return plainDateFromDate(d);
+}
+
+function compare(a: PlainDate, b: PlainDate): number {
+ if (a.year !== b.year) {
+ return a.year - b.year;
+ }
+ if (a.month !== b.month) {
+ return a.month - b.month;
+ }
+ return a.day - b.day;
+}
+
+export function plainDateIsBefore(a: PlainDate, b: PlainDate): boolean {
+ return compare(a, b) < 0;
+}
+
+export function plainDateIsAfter(a: PlainDate, b: PlainDate): boolean {
+ return compare(a, b) > 0;
+}
+
+export function plainDateIsEqual(a: PlainDate, b: PlainDate): boolean {
+ return compare(a, b) === 0;
+}
+
+export function plainDateIsInRange(
+ pd: PlainDate,
+ range: [PlainDate, PlainDate],
+): boolean {
+ return compare(pd, range[0]) >= 0 && compare(pd, range[1]) <= 0;
+}
+
+export function plainDateSetFirstOfMonth(pd: PlainDate): PlainDate {
+ return {year: pd.year, month: pd.month, day: 1};
+}
+
+export function plainDateGetWeekNumber(pd: PlainDate): number {
+ const d = plainDateToDate(pd);
+ const dayNum = d.getDay() || 7;
+ d.setDate(d.getDate() + 4 - dayNum);
+ const yearStart = new Date(d.getFullYear(), 0, 1);
+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+}
+
+// e.g. "Wednesday, May 21, 2026" (locale-dependent)
+export const DATE_FORMAT_WITH_WEEKDAY: Intl.DateTimeFormatOptions = {
+ weekday: 'long',
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+};
+
+// e.g. "May 21, 2026" (locale-dependent)
+export const DATE_FORMAT_LONG: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+};
+
+// e.g. "January 2026" (locale-dependent)
+export const DATE_FORMAT_MONTH_YEAR: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: 'long',
+};
+
+// e.g. "Jan 25" (locale-dependent)
+export const DATE_FORMAT_SHORT: Intl.DateTimeFormatOptions = {
+ month: 'short',
+ day: 'numeric',
+};
+
+// e.g. "Jan 25, 2026" (locale-dependent)
+export const DATE_FORMAT_SHORT_WITH_YEAR: Intl.DateTimeFormatOptions = {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+};
+
+export function plainDateFormat(
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+): string {
+ return new Intl.DateTimeFormat(undefined, options).format(
+ plainDateToDate(pd),
+ );
+}