|
import { parseISO, isValid } from 'date-fns'; |
|
import { zonedTimeToUtc, utcToZonedTime } from 'date-fns-tz'; |
|
|
|
export const getDeadlineInLocalTime = (deadline: string | undefined, timezone: string | undefined): Date | null => { |
|
if (!deadline || deadline === 'TBD') { |
|
return null; |
|
} |
|
|
|
try { |
|
|
|
const parsedDate = parseISO(deadline); |
|
|
|
if (!isValid(parsedDate)) { |
|
console.error('Invalid date parsed from deadline:', deadline); |
|
return null; |
|
} |
|
|
|
|
|
const normalizeTimezone = (tz: string | undefined): string => { |
|
if (!tz) return 'UTC'; |
|
|
|
|
|
if (tz === 'AoE') return '-12:00'; |
|
|
|
|
|
if (!tz.toUpperCase().startsWith('UTC')) return tz; |
|
|
|
|
|
const match = tz.match(/^UTC([+-])(\d+)$/); |
|
if (match) { |
|
const [, sign, hours] = match; |
|
const paddedHours = hours.padStart(2, '0'); |
|
return `${sign}${paddedHours}:00`; |
|
} |
|
|
|
|
|
if (tz === 'UTC+0' || tz === 'UTC-0' || tz === 'UTC+00' || tz === 'UTC-00') { |
|
return 'UTC'; |
|
} |
|
|
|
return 'UTC'; |
|
}; |
|
|
|
const normalizedTimezone = normalizeTimezone(timezone); |
|
|
|
try { |
|
|
|
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const utcDate = zonedTimeToUtc(parsedDate, normalizedTimezone); |
|
|
|
|
|
const localDate = utcToZonedTime(utcDate, userTimezone); |
|
|
|
return isValid(localDate) ? localDate : null; |
|
} catch (error) { |
|
console.error('Timezone conversion error:', error); |
|
return parsedDate; |
|
} |
|
} catch (error) { |
|
console.error('Error processing deadline:', error); |
|
return null; |
|
} |
|
}; |