Files
Novault-Frontend-web/src/utils/dateUtils.ts

81 lines
2.6 KiB
TypeScript

/**
* Date Utilities
* Handles local date formatting and manipulation to avoid UTC timezone issues.
*/
/**
* Formats a date object to 'YYYY-MM-DD' string using local time.
* Replaces: date.toISOString().split('T')[0]
*/
export function toLocalDateString(date: Date | string | number): string {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
/**
* Checks if two dates refer to the same day in local time.
*/
export function isSameDay(date1: Date | string, date2: Date | string): boolean {
const d1 = new Date(date1);
const d2 = new Date(date2);
return (
d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate()
);
}
/**
* Returns a new Date object set to the start of the day (00:00:00.000) in local time.
*/
export function getStartOfDay(date: Date = new Date()): Date {
const d = new Date(date);
d.setHours(0, 0, 0, 0);
return d;
}
/**
* Returns a new Date object set to the end of the day (23:59:59.999) in local time.
*/
export function getEndOfDay(date: Date = new Date()): Date {
const d = new Date(date);
d.setHours(23, 59, 59, 999);
return d;
}
/**
* Calculates date range helpers
*/
export const DateRanges = {
today: () => {
const start = getStartOfDay();
const end = getEndOfDay();
return { start, end, startStr: toLocalDateString(start), endStr: toLocalDateString(end) };
},
yesterday: () => {
const start = getStartOfDay();
start.setDate(start.getDate() - 1);
const end = getEndOfDay(start);
return { start, end, startStr: toLocalDateString(start), endStr: toLocalDateString(end) };
},
thisWeek: () => {
const now = new Date();
const day = now.getDay() || 7; // Sunday is 0, make it 7 for ISO week (Mon-Sun)? Or standard week. Let's assume Mon start.
const start = getStartOfDay();
if (day !== 1) {
start.setDate(now.getDate() - day + 1 + (day === 0 ? -7 : 0)); // Move to Monday
}
const end = getEndOfDay();
return { start, end, startStr: toLocalDateString(start), endStr: toLocalDateString(end) };
},
thisMonth: () => {
const now = new Date();
const start = getStartOfDay(new Date(now.getFullYear(), now.getMonth(), 1));
const end = getEndOfDay(new Date(now.getFullYear(), now.getMonth() + 1, 0));
return { start, end, startStr: toLocalDateString(start), endStr: toLocalDateString(end) };
}
};