Skip to content

Commit

Permalink
Add a bit more rigid handling and error checking to utils/dates. Add …
Browse files Browse the repository at this point in the history
…jest tests.
  • Loading branch information
dannon committed Dec 9, 2024
1 parent 09cca14 commit f164918
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
41 changes: 41 additions & 0 deletions client/src/utils/dates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { formatGalaxyPrettyDateString, galaxyTimeToDate, localizeUTCPretty } from "./dates";

describe("dates.ts", () => {
describe("galaxyTimeToDate", () => {
it("should convert valid galaxyTime string to Date object", () => {
const galaxyTime = "2023-10-01T12:00:00";
const date = galaxyTimeToDate(galaxyTime);
expect(date).toBeInstanceOf(Date);
expect(date.toISOString()).toBe("2023-10-01T12:00:00.000Z");
});

it("should append Z if missing and parse correctly", () => {
const galaxyTime = "2023-10-01T12:00:00";
const date = galaxyTimeToDate(galaxyTime);
expect(date.toISOString()).toBe("2023-10-01T12:00:00.000Z");
});

it("should throw an error for invalid galaxyTime string", () => {
const invalidGalaxyTime = "invalid-date-string";
expect(() => galaxyTimeToDate(invalidGalaxyTime)).toThrow(
`Invalid galaxyTime string: ${invalidGalaxyTime}`
);
});
});

describe("localizeUTCPretty", () => {
it("should format Date object into human-readable string", () => {
const date = new Date("2023-10-01T12:00:00Z");
const formatted = localizeUTCPretty(date);
expect(formatted).toBe("Sunday Oct 1st 8:00:00 2023 GMT-4");
});
});

describe("formatGalaxyPrettyDateString", () => {
it("should convert galaxyTime string to formatted date string", () => {
const galaxyTime = "2023-10-01T12:00:00";
const formatted = formatGalaxyPrettyDateString(galaxyTime);
expect(formatted).toBe("Sunday Oct 1st 8:00:00 2023 GMT-4");
});
});
});
14 changes: 9 additions & 5 deletions client/src/utils/dates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ import { format, parseISO } from "date-fns";
* @returns {Date} The parsed Date object.
*/
export function galaxyTimeToDate(galaxyTime: string): Date {
// We likely don't have tzinfo, but this will always be UTC coming
// from Galaxy so append Z to assert that prior to parsing
if (!galaxyTime.endsWith("Z")) {
galaxyTime += "Z";
// Galaxy doesn't include Zulu time zone designator, but it's always UTC
// so we need to add it to parse the string correctly in JavaScript.
let time = galaxyTime;
if (!time.endsWith("Z")) {
time += "Z";
}
const date = parseISO(time);
if (isNaN(date.getTime())) {
throw new Error(`Invalid galaxyTime string: ${galaxyTime}`);
}
const date = parseISO(galaxyTime);
return date;
}

Expand Down

0 comments on commit f164918

Please sign in to comment.