RFP_Space_V05 / lib /datetime-utils.ts
Varun10000's picture
Upload 89 files
17cf14d verified
Raw
History Blame Contribute Delete
3.01 kB
// Timezone-aware datetime utilities (similar to your Python datetime_utils.py)
/**
* Get current time in configured timezone
*/
export function nowTz(): Date {
return new Date()
}
/**
* Calculate days until a target date
*/
export function daysUntil(target: Date | string): number {
const targetDate = typeof target === 'string' ? new Date(target) : target
const now = new Date()
const diffTime = targetDate.getTime() - now.getTime()
return Math.floor(diffTime / (1000 * 60 * 60 * 24))
}
/**
* Calculate hours until a target date
*/
export function hoursUntil(target: Date | string): number {
const targetDate = typeof target === 'string' ? new Date(target) : target
const now = new Date()
const diffTime = targetDate.getTime() - now.getTime()
return diffTime / (1000 * 60 * 60)
}
/**
* Check if current time is within a window around target time
* @param target Target datetime
* @param windowMinutes Window size in minutes (default: 60)
* @returns True if now is between [target - window, target + window]
*/
export function isWithinWindow(target: Date | string, windowMinutes: number = 60): boolean {
const targetDate = typeof target === 'string' ? new Date(target) : target
const now = new Date()
const diffMs = Math.abs(now.getTime() - targetDate.getTime())
return diffMs <= windowMinutes * 60 * 1000
}
/**
* Add hours to a date
*/
export function addHours(date: Date | string, hours: number): Date {
const d = typeof date === 'string' ? new Date(date) : new Date(date)
d.setHours(d.getHours() + hours)
return d
}
/**
* Add days to a date
*/
export function addDays(date: Date | string, days: number): Date {
const d = typeof date === 'string' ? new Date(date) : new Date(date)
d.setDate(d.getDate() + days)
return d
}
/**
* Format date for display with timezone
*/
export function formatDateTz(date: Date | string | null | undefined, options?: Intl.DateTimeFormatOptions): string {
if (!date) return 'N/A'
const d = typeof date === 'string' ? new Date(date) : date
return d.toLocaleString('en-US', {
timeZone: process.env.NEXT_PUBLIC_TIMEZONE || 'America/New_York',
...options,
})
}
/**
* Check if a date is in the past
*/
export function isPast(date: Date | string): boolean {
const d = typeof date === 'string' ? new Date(date) : date
return d.getTime() < Date.now()
}
/**
* Check if a date is in the future
*/
export function isFuture(date: Date | string): boolean {
return !isPast(date)
}
/**
* Get start of day for a date
*/
export function startOfDay(date: Date | string): Date {
const d = typeof date === 'string' ? new Date(date) : new Date(date)
d.setHours(0, 0, 0, 0)
return d
}
/**
* Get end of day for a date
*/
export function endOfDay(date: Date | string): Date {
const d = typeof date === 'string' ? new Date(date) : new Date(date)
d.setHours(23, 59, 59, 999)
return d
}