Last active
July 12, 2021 14:59
-
-
Save jsjoeio/7172a54b4596987a4272860306763b94 to your computer and use it in GitHub Desktop.
Timezone related functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
fromUnixTime, | |
format, | |
} from "date-fns" | |
/** | |
* Checks if a timezone string is valid or not | |
* | |
* We do this to catch typos. | |
* | |
* Source: https://stackoverflow.com/a/44118363/3015595 | |
**/ | |
export function isValidTimezone(tz: string) { | |
if (!tz) { | |
console.error(`No timezone provided: ${tz}`) | |
return false | |
} | |
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) { | |
throw "Time zones are not available in this environment" | |
} | |
try { | |
Intl.DateTimeFormat(undefined, { timeZone: tz }) | |
return true | |
} catch (e) { | |
console.info(`Invalid timezone: ${tz}`) | |
return false | |
} | |
} | |
/** | |
* Gets the date from the unix timestamp | |
* Returns null if no date | |
**/ | |
export function getDateFromUnixTimestamp(date: number | undefined) { | |
if (!date) { | |
return null | |
} | |
return fromUnixTime(date) | |
} | |
declare const _date: unique symbol | |
export type DateInTimezone = Date & { readonly [_date]: Date } | |
// Source: https://stackoverflow.com/a/54127122/3015595 | |
export function convertTZ( | |
date: Date | string, | |
tzString: string | |
): DateInTimezone { | |
return new Date( | |
(typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", { | |
timeZone: tzString, | |
}) | |
) as DateInTimezone | |
} | |
export function isSameDay(messageDate: Date, expectedDate: Date) { | |
return messageDate.getDate() === expectedDate.getDate() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment