Skip to content

Instantly share code, notes, and snippets.

@jhmaster2000
Last active November 6, 2021 23:56
Show Gist options
  • Save jhmaster2000/539750fc36d104b232b44e978dff625c to your computer and use it in GitHub Desktop.
Save jhmaster2000/539750fc36d104b232b44e978dff625c to your computer and use it in GitHub Desktop.
Fast and simple JS/TS Date timezone conversion with no dependencies
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());
@jhmaster2000
Copy link
Author

jhmaster2000 commented Nov 6, 2021

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.

  • tz: The timezone as a UTC offset. Defaults to 0 (UTC).
  • date: A date object to convert to the given timezone. If not provided one will be created with the current time.

Returns a native Date object with all relevant data (See "Caveats" below) converted to the given timezone.

import TZDate from './tzdate';

const dateUTC: Date = TZDate(0);     // UTC (https://www.timeanddate.com/time/zones/gmt)
const dateEST: Date = TZDate(-5);    // UTC -5 (https://www.timeanddate.com/time/zones/est)
const dateNPT: Date = TZDate(-5.75); // UTC -5:45 (https://www.timeanddate.com/time/zones/npt)
const dateAMT: Date = TZDate(4);     // UTC +4 (https://www.timeanddate.com/time/zones/amt-armenia)
const dateAFT: Date = TZDate(4.5);   // UTC +4:30 (https://www.timeanddate.com/time/zones/aft)
const dateLNT: Date = TZDate(14);    // UTC +14 (https://www.timeanddate.com/time/zones/lint)

Caveats

This is a quick and dirty hack for timezone conversion without a big library, so of course it doesn't cover everything:

tzdate here refers to a Date object returned by the TZDate() function, not the function itself.

  • 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.
    • Eg: If your local TZ is UTC -3, meaning an offset towards UTC of +3, and you request a tzdate of UTC +7, getUTC###() methods will return values for the UTC +10 timezone).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment