Skip to content

Instantly share code, notes, and snippets.

@devwolf75
Created February 14, 2020 04:24
Show Gist options
  • Save devwolf75/4b12bb06bd9df9c4775cdfd6f15f4d6a to your computer and use it in GitHub Desktop.
Save devwolf75/4b12bb06bd9df9c4775cdfd6f15f4d6a to your computer and use it in GitHub Desktop.
Typescript function that takes a Date, string or moment object and converts it between timezones.
import * as moment from "moment-timezone";
/**
* @description
* @param {Date | string | moment} date Date to transform.
* @param {string} originTZ Timezone in which the date to transform is currently. I.E. "UTC". Defaults to client PC TZ.
* @param {string} destinationTZ Timezone to which to convert the date. I.E. "America/Los Angeles". Defaults to "UTC".
* @return {string} Date converted to destination timezone in string.
*
*/
export function toTimezone(date: Date | string | moment, originTZ: string = Intl.DateTimeFormat().resolvedOptions().timeZone, destinationTZ: string = "UTC"): string {
return moment(moment(new Date()).tz(originTz, true))
.tz(destinationTZ)
.format("YYYY-MM-DDTHH:mm:ss");
}
// console.log(toTimezone(new Date(), Intl.DateTimeFormat().resolvedOptions().timeZone, "UTC")) // Current PC time to UTC.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment