Skip to content

Instantly share code, notes, and snippets.

@EricHech
Created July 15, 2021 05:18
Show Gist options
  • Save EricHech/f7cfab035f7d53619e5de86d3933f1a1 to your computer and use it in GitHub Desktop.
Save EricHech/f7cfab035f7d53619e5de86d3933f1a1 to your computer and use it in GitHub Desktop.
export const getGmtDiff = (timeZone: typeof IANNA_TIME_ZONES[number]["key"]) => {
const date = new Date();
const GMT_TIME_UTC_DATE = date.getUTCDate();
const GMT_TIME_HOURS = date.getUTCHours();
const GMT_TIME_MIN = date.getUTCMinutes();
const timeZoneDate = new Date(new Date().toLocaleString("en-US", { timeZone }));
const h = timeZoneDate.getHours();
// NOTE: Remember that adding a negative number subtracts
let dateLineOffset = 0;
if (timeZoneDate.getDate() < GMT_TIME_UTC_DATE) dateLineOffset = -24;
if (timeZoneDate.getDate() > GMT_TIME_UTC_DATE) dateLineOffset = 24;
const hrs = h - GMT_TIME_HOURS + dateLineOffset;
let plusOrMinus = " ";
if (hrs > 0) plusOrMinus = "+";
if (hrs < 0) plusOrMinus = "-";
// NOTE: Remember that adding a negative number subtracts
const minDiff = timeZoneDate.getMinutes() - GMT_TIME_MIN;
const hrsAccountingMinutes = minDiff < 0 ? hrs + minutes(minDiff).in("hours") : hrs;
// NOTE: Remember that adding a negative number subtracts
const finalHours = String(Math.abs(Math.floor(hrsAccountingMinutes))).padStart(2, "0");
const finalMinutes = String(minDiff < 0 ? 60 + minDiff : minDiff).padStart(2, "0");
return `(GMT${plusOrMinus}${finalHours}:${finalMinutes})`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment