Created
May 4, 2020 03:00
-
-
Save JuanM04/d0e5a38b6bfbab7a997cb7b7ec15dd59 to your computer and use it in GitHub Desktop.
Timezone Shifter
This file contains hidden or 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
/** | |
* Shift any Date timezone. | |
* @param {Date} date - Date to update. | |
* @param {string} timezone - Timezone as `-03:00`. | |
*/ | |
function timezoneShifter(date, timezone) { | |
let isBehindGTM = false; | |
if (timezone.startsWith("-")) { | |
timezone = timezone.substr(1); | |
isBehindGTM = true; | |
} | |
const [hDiff, mDiff] = timezone.split(":").map((t) => parseInt(t)); | |
const diff = hDiff * 60 + mDiff * (isBehindGTM ? 1 : -1); | |
const currentDiff = new Date().getTimezoneOffset(); | |
return new Date(date.valueOf() + (currentDiff - diff) * 60 * 1000); | |
} |
This file contains hidden or 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
/** | |
* Shift any Date timezone. | |
* @param {Date} date - Date to update. | |
* @param {string} timezone - Timezone as `-03:00`. | |
*/ | |
function timezoneShifter(date: Date, timezone: string): Date { | |
let isBehindGTM = false; | |
if (timezone.startsWith("-")) { | |
timezone = timezone.substr(1); | |
isBehindGTM = true; | |
} | |
const [hDiff, mDiff] = timezone.split(":").map((t) => parseInt(t)); | |
const diff = hDiff * 60 + mDiff * (isBehindGTM ? 1 : -1); | |
const currentDiff = new Date().getTimezoneOffset(); | |
return new Date(date.valueOf() + (currentDiff - diff) * 60 * 1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment