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

fix: extract offset from Intl.DateTimeFormat from "GMT" #12

Merged
merged 1 commit into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/tzOffset/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function tzOffset(timeZone: string | undefined, date: Date): number {
{ timeZone, hour: "numeric", timeZoneName: "longOffset" }
).format);

const offsetStr = format(date).slice(6);
const offsetStr = format(date).split('GMT')[1] || '';
if (offsetStr in offsetCache) return offsetCache[offsetStr]!;

return calcOffset(offsetStr, offsetStr.split(":"));
Expand Down
35 changes: 34 additions & 1 deletion src/tzOffset/tests.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { tzOffset } from "./index.ts";

describe("tzOffset", () => {
Expand Down Expand Up @@ -87,4 +87,37 @@ describe("tzOffset", () => {
expect(tzOffset("Australia/Adelaide", date)).toBe(570);
});
});

describe('Intl.DateTimeFormat format', () => {
let mockFormat = vi.fn();
beforeEach(() => {
mockFormat = vi.fn(() => '5 GMT+08:00');
const dtf = new Intl.DateTimeFormat();
vi.spyOn(Intl, 'DateTimeFormat').mockImplementation(() => {
return { ...dtf, format: mockFormat };
});
});

afterEach(() => {
vi.mocked(Intl.DateTimeFormat).mockRestore();
});

it("reads offset from expected format", () => {
mockFormat.mockReturnValue('5 GMT+08:00');
const date = new Date("2020-01-15T00:00:00Z");
expect(tzOffset("Asia/Manila", date)).toBe(480);
});

it("reads offset from polyfill", () => {
mockFormat.mockReturnValue('5:53 PM GMT-9:30');
const date = new Date("2020-01-15T00:00:00Z");
expect(tzOffset("Pacific/Marquesas", date)).toBe(-570);
});

it("reads offset from polyfill (without offset)", () => {
mockFormat.mockReturnValue('5:53 PM GMT');
const date = new Date("2020-01-15T00:00:00Z");
expect(tzOffset("UTC", date)).toBe(0);
});
})
});