Skip to content

Commit 8219814

Browse files
committed
Enhance parseDate function to support additional time formats and improve UTC handling in tests
1 parent 116de15 commit 8219814

3 files changed

Lines changed: 23 additions & 3 deletions

File tree

src/helpers/parseDate.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ describe("parseDate", () => {
107107
expect(parseDate("2000-02-21T00:00:01", { asUTC: true })).toStrictEqual(
108108
new Date("2000-02-21T00:00:01.000Z")
109109
);
110+
111+
expect(
112+
parseDate("2000-02-21T00:00:01.001", { asUTC: true })
113+
).toStrictEqual(new Date("2000-02-21T00:00:01.001Z"));
114+
115+
expect(
116+
parseDate("2000-02-21T00:00:01.001Z") // no asUTC
117+
).toStrictEqual(new Date("2000-02-21T00:00:01.001Z"));
118+
119+
expect(
120+
parseDate("2000-02-21T00:00:01.001Z", { asUTC: true }) // asUTC
121+
).toStrictEqual(new Date("2000-02-21T00:00:01.001Z"));
110122
});
111123
});
112124

src/helpers/parseDate.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import { isNumber } from "../validators/isNumber";
66
import { isString } from "../validators/isString";
77

88
const partialDateRegex = /^\d{4}(-\d{2})?(-\d{2})?$/;
9+
// Matches complete date-time without timezone: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS or YYYY-MM-DDTHH:MM:SS.mmm
10+
// Does NOT match dates ending with Z or +/-HH:MM timezone offsets
11+
const noTimezoneRegex = /^(?!.*(?:Z|[+-]\d{2}:?\d{2})).+$/;
912

1013
/**
1114
*
@@ -42,17 +45,21 @@ export const parseDate = (
4245
}T00:00:00`;
4346
}
4447

48+
// Now check that time is complete (JS can parse HH:mm but not HH)
4549
const [date, time] = arg.split("T");
46-
// 8 as in "HH:MM:SS"
47-
if (time.length < 8) {
50+
// 8 as in "HH:MM:SS" (actually, just HH:mm would be enough, but better be safe)
51+
// time is undefined for crappy strings like "hello-I-am-a-date"
52+
if (time?.length < 8) {
4853
arg = `${date}T${time}${"00:00:00".slice(time.length)}`;
4954
}
5055

51-
if (options?.asUTC) {
56+
if (options?.asUTC && noTimezoneRegex.test(arg)) {
5257
arg += "Z"; // In this case, force UTC
5358
}
5459
}
5560

61+
console.log(arg);
62+
5663
const date = new Date(arg!); // ! => isEmpty cannot narrow type
5764

5865
if (!isJsDate(date)) return;

src/validators/isSameUTCDay.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export const isSameUTCDay = (
1919
const date2UTC = parseDate(date2Input, { asUTC: true });
2020
if (!date1UTC || !date2UTC) return false;
2121

22+
console.log(date1UTC.toISOString(), date2UTC.toISOString());
2223
return (
2324
date1UTC.getUTCFullYear() === date2UTC.getUTCFullYear() &&
2425
date1UTC.getUTCMonth() === date2UTC.getUTCMonth() &&

0 commit comments

Comments
 (0)