Skip to content

Instantly share code, notes, and snippets.

@johnloy
Created May 3, 2021 21:24
Show Gist options
  • Save johnloy/9b6133552a4e8f76a90f3b765965baad to your computer and use it in GitHub Desktop.
Save johnloy/9b6133552a4e8f76a90f3b765965baad to your computer and use it in GitHub Desktop.
// tzName is one of the tz database names at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
// Example: 'Pacific/Honolulu' (UTC-10)
function getUTCOffset(tzName, date) {
date = new Date(date || Date.now());
date.setMilliseconds(0);
// 1) Get the local UTC offset
// ---------------------------
// Convert date UTC offset to true hours offset.
// Date.prototype.getTimezoneOffset() confusingly returns positive
// values for earlier time offsets and negative for later.
const localOffsetHrs = (date.getTimezoneOffset() / 60) * -1;
// 2) Get a parseable date string for the provided date's time in the desired timezone
// -----------------------
// new Date().toLocaleString('en-US', { timeZone: 'Pacific/Honolulu' } )
// -> "5/3/2021, 11:04:57 AM"
const thereLocaleStr = date.toLocaleString("en-US", {
timeZone: tzName
});
// 3) Get the offset difference for local and timezone
const tzDate = new Date(thereLocaleStr);
const diffHrs = (tzDate.getTime() - date.getTime()) / 1000 / 60 / 60;
// 4) Use the difference to adjust the local offset
const tzOffsetHrs = localOffsetHrs + diffHrs;
return tzOffsetHrs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment