Skip to content

Instantly share code, notes, and snippets.

@manavm1990
Last active May 24, 2024 03:10
Show Gist options
  • Save manavm1990/e64196aa68213755d84a9abb62e03b85 to your computer and use it in GitHub Desktop.
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.
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);
});
});
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