Skip to content

Instantly share code, notes, and snippets.

@jhmaster2000
Last active November 6, 2021 23:56

Revisions

  1. jhmaster2000 revised this gist Nov 6, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tzdate.ts
    Original file line number Diff line number Diff line change
    @@ -11,7 +11,7 @@ function formatTZOffset(offset: number): string {
    return hours.toString().padStart(2, '0') + mins.toString().padStart(2, '0');
    }

    function TZDate(tz: number = 0, date: Date = new Date()): Date {
    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;
  2. jhmaster2000 created this gist Nov 6, 2021.
    25 changes: 25 additions & 0 deletions tzdate.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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');
    }

    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());