Skip to content

Instantly share code, notes, and snippets.

@JuanM04
Created May 4, 2020 03:00
Show Gist options
  • Save JuanM04/d0e5a38b6bfbab7a997cb7b7ec15dd59 to your computer and use it in GitHub Desktop.
Save JuanM04/d0e5a38b6bfbab7a997cb7b7ec15dd59 to your computer and use it in GitHub Desktop.
Timezone Shifter
/**
* 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);
}
/**
* 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