Last active
November 6, 2021 23:56
-
-
Save jhmaster2000/539750fc36d104b232b44e978dff625c to your computer and use it in GitHub Desktop.
Fast and simple JS/TS Date timezone conversion with no dependencies
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
const input = Number(process.argv[2]) || undefined; | |
function formatTZOffset(offset: number): string { | |
offset = Math.abs(offset); | |
let hours = Math.trunc(offset); | |
let mins = Math.round((offset - hours) * 60); | |
if (mins === 60) { | |
hours++; | |
mins = 0; | |
} | |
return hours.toString().padStart(2, '0') + mins.toString().padStart(2, '0'); | |
} | |
export default function TZDate(tz: number = 0, date: Date = new Date()): Date { | |
if (tz < -12 || tz > 14) throw new Error(`Invalid timezone "${tz}". Valid timezones between -12 and +14.`); | |
const calculatedTZ: number = date.getTimezoneOffset() / 60 + tz; | |
const tzString: string = (calculatedTZ > 0 ? '-' : '+') + formatTZOffset(calculatedTZ); | |
return new Date(Date.parse(date.toUTCString() + tzString)); | |
} | |
console.log('Input:', input); | |
console.log(TZDate(input).toString()); | |
console.log(TZDate(input, new Date(0)).toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
CLI:
ts-node tzdate.ts <UTC offset>
...or after compiling to JS:
node tzdate.js <UTC offset>
Code
TZDate(tz?: number, date?: Date): Date
Both arguments are optional.
0
(UTC).Caveats
This is a quick and dirty hack for timezone conversion without a big library, so of course it doesn't cover everything:
tzdate.toString()
and alike methods will correctly display the requested timezone's date and time, but the user's local timezone GMT offset indicator and name (eg:"... GMT-0500 (Eastern Standard Time)"
) will still be appended at the end as misleading information.tzdate.getUTC###()
methods will not work as expected due to expecting the stored date and time to be on the user's local timezone, they will instead just return the value of the TZ relative to the requested TZ of the tzdate, offset by the user's local TZ offset towards UTC.UTC -3
, meaning an offset towards UTC of +3, and you request a tzdate ofUTC +7
,getUTC###()
methods will return values for theUTC +10
timezone).