Skip to content

Commit

Permalink
chore: Speed up dayjs#tz() (iamkun#1074)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonmd committed Sep 26, 2020
1 parent 16816a3 commit e248f33
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ const typeToPos = {

const ms = 'ms'

export default (o, c, d) => {
let defaultTimezone

const localUtcOffset = d().utcOffset()

const makeFormatParts = (timestamp, timezone, option = {}) => {
const date = new Date(timestamp)
const dtf = new Intl.DateTimeFormat('en-US', {
// Cache time-zone lookups from Intl.DateTimeFormat,
// as it is a *very* slow method.
const dtfCache = {}
const getDateTimeFormat = (timezone, options = {}) => {
const timeZoneName = options.timeZoneName || 'short'
const key = `${timezone}|${timeZoneName}`
let dtf = dtfCache[key]
if (!dtf) {
dtf = new Intl.DateTimeFormat('en-US', {
hour12: false,
timeZone: timezone,
year: 'numeric',
Expand All @@ -25,8 +26,21 @@ export default (o, c, d) => {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: option.timeZoneName || 'short'
timeZoneName
})
dtfCache[key] = dtf
}
return dtf
}

export default (o, c, d) => {
let defaultTimezone

const localUtcOffset = d().utcOffset()

const makeFormatParts = (timestamp, timezone, options = {}) => {
const date = new Date(timestamp)
const dtf = getDateTimeFormat(timezone, options)
return dtf.formatToParts(date)
}

Expand Down

0 comments on commit e248f33

Please sign in to comment.