Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TehShrike/61ea0820354df2d4d56f5a102623e4de to your computer and use it in GitHub Desktop.
Save TehShrike/61ea0820354df2d4d56f5a102623e4de to your computer and use it in GitHub Desktop.
get_timezone_offset_for_point_in_time
// from https://github.com/bsvetlik/date-fns-tz/blob/eb2bb6209931c5abe1cfcdf2faaa41de5493648a/src/_lib/tzParseTimezone/index.js#L86-L98
export default (iana_timezone_string, date_object) => {
const [ year, month, day, hour, minute, second ] = tz_tokenize_date(
date_object,
iana_timezone_string,
)
const asUTC = Date.UTC(year, month - 1, day, hour, minute, second, date_object.getMilliseconds())
return asUTC - date_object.getTime()
}
// lifted/trimmed from https://github.com/marnusw/date-fns-tz/blob/1d871f2c7ca76733552d5e22371a5fedcbe3c49f/src/_lib/tzTokenizeDate/index.js
const tz_tokenize_date = (date, timeZone) => partsOffset(getDateTimeFormat(timeZone), date)
const typeToPos = {
year: 0,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
}
function partsOffset(dtf, date) {
const formatted = dtf.formatToParts(date)
const filled = []
for (let i = 0; i < formatted.length; i++) {
const pos = typeToPos[formatted[i].type]
if (pos >= 0) {
filled[pos] = parseInt(formatted[i].value, 10)
}
}
return filled
}
// Get a cached Intl.DateTimeFormat instance for the IANA `timeZone`. This can be used
// to get deterministic local date/time output according to the `en-US` locale which
// can be used to extract local time parts as necessary.
const dtfCache = {}
function getDateTimeFormat(timeZone) {
if (!dtfCache[timeZone]) {
dtfCache[timeZone] = new Intl.DateTimeFormat(`en-US`, {
hourCycle: `h23`,
timeZone,
year: `numeric`,
month: `2-digit`,
day: `2-digit`,
hour: `2-digit`,
minute: `2-digit`,
second: `2-digit`,
})
}
return dtfCache[timeZone]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment