Last active
May 24, 2024 03:10
-
-
Save manavm1990/e64196aa68213755d84a9abb62e03b85 to your computer and use it in GitHub Desktop.
Removing timezone offsets before formatting/parsing date-time strings with `date-fns`, etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { describe, expect, it } from "vitest"; | |
import { removeTimezoneOffset } from "."; | |
describe("removeTimezoneOffset", () => { | |
it("should remove timezone offset in format -07:00", () => { | |
const dateTime = "2024-06-15T17:30:00-07:00"; | |
const expected = "2024-06-15T17:30:00"; | |
expect(removeTimezoneOffset(dateTime)).toBe(expected); | |
}); | |
it("should remove timezone offset in format +07:00", () => { | |
const dateTime = "2024-06-15T17:30:00+07:00"; | |
const expected = "2024-06-15T17:30:00"; | |
expect(removeTimezoneOffset(dateTime)).toBe(expected); | |
}); | |
it("should remove timezone offset in format -0700", () => { | |
const dateTime = "2024-06-15T17:30:00-0700"; | |
const expected = "2024-06-15T17:30:00"; | |
expect(removeTimezoneOffset(dateTime)).toBe(expected); | |
}); | |
it("should remove timezone offset in format +0700", () => { | |
const dateTime = "2024-06-15T17:30:00+0700"; | |
const expected = "2024-06-15T17:30:00"; | |
expect(removeTimezoneOffset(dateTime)).toBe(expected); | |
}); | |
it("should remove milliseconds and Z", () => { | |
const dateTime = "2019-12-15T20:00:00.000Z"; | |
const expected = "2019-12-15T20:00:00"; | |
expect(removeTimezoneOffset(dateTime)).toBe(expected); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function removeTimezoneOffset(dateTime: string): string { | |
return dateTime.replace( | |
/-\d{2}:\d{2}$|\+\d{2}:\d{2}$|-\d{4}$|\+\d{4}$|\.\d+Z$/, | |
"", | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment