Skip to content

Commit 9f4960d

Browse files
allohamorakossnocorp
authored andcommitted
fix: add America/St_Johns handling to tzOffset
1 parent bff7b8a commit 9f4960d

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/tzOffset/index.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,14 @@ export function tzOffset(timeZone: string | undefined, date: Date): number {
2525
const offsetStr = format(date).slice(6);
2626
if (offsetStr in offsetCache) return offsetCache[offsetStr]!;
2727

28-
const [hours, minutes] = offsetStr.split(":").map(Number);
29-
return (offsetCache[offsetStr] = hours! * 60 + (minutes || 0));
28+
const [hours, minutes = 0] = offsetStr.split(":").map(Number);
29+
30+
// type-guard
31+
if (hours === undefined) {
32+
return NaN;
33+
}
34+
35+
return (offsetCache[offsetStr] = hours > 0 ? hours * 60 + minutes : hours * 60 - minutes);
3036
} catch {
3137
return NaN;
3238
}

src/tzOffset/tests.ts

+10
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@ describe("tzOffset", () => {
3939
expect(tzOffset("Europe/London", date)).toBe(0);
4040
});
4141

42+
it('works with America/St_Johns for Daylight Saving Time', () => {
43+
const date = new Date("2023-03-15T18:00:00.000Z");
44+
expect(tzOffset("America/St_Johns", date)).toBe(-150);
45+
});
46+
47+
it('works America/St_Johns for Standard Time', () => {
48+
const date = new Date("2023-03-03T18:00:00.000Z");
49+
expect(tzOffset("America/St_Johns", date)).toBe(-210);
50+
});
51+
4252
it("returns NaN if the offset the date or time zone are invalid", () => {
4353
expect(tzOffset("Etc/Invalid", new Date("2020-01-15T00:00:00Z"))).toBe(NaN);
4454
expect(tzOffset("America/New_York", new Date(NaN))).toBe(NaN);

0 commit comments

Comments
 (0)