Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsOffset may fail depending on the Intl.DateTimeFormat implementation #23

Open
martin-trummer opened this issue Oct 16, 2024 · 2 comments

Comments

@martin-trummer
Copy link

tz/src/tzOffset/index.ts

Lines 18 to 23 in 2139037

export function tzOffset(timeZone: string | undefined, date: Date): number {
try {
const format = (offsetFormatCache[timeZone!] ||= new Intl.DateTimeFormat(
"en-GB",
{ timeZone, hour: "numeric", timeZoneName: "longOffset" }
).format);

The problem is that the format function is not bound to the class. So if the implementation for format() uses this, it will fail at runtime.

We can see the issue, when we use the Time Travel Chrom Extension which is very useful for testing

possible fix would be

function getBoundFormat(timeZone: string) {
  const dateTimeFormat = new Intl.DateTimeFormat("en-GB", {
    timeZone,
    hour: "numeric",
    timeZoneName: "longOffset"
  })
  return dateTimeFormat.format.bind(dateTimeFormat);
}

export function tzOffset(timeZone, date) {
  try {
    const format = offsetFormatCache[timeZone] ||= getBoundFormat(timeZone);
@Perdolique
Copy link

@kossnocorp which browsers are supported? I see that longOffset isn't supported in Safari below 15.4 and Chrome below 95, for example, but can't find a compatibility table in the documentation.

@csandman
Copy link

@Perdolique Thanks for the tip on longOffset, I'm currently dealing with some production bugs due to this, as I didn't realize it would return NaN for browsers before that. I'm currently looking into formatjs for a polyfill approach, but I'm not sure the best way to actually test on one of these older browsers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants