Skip to content

Commit 0e0f721

Browse files
authored
fix: Incomplete date-times are encoded as iso-formatted date-time (#171)
1 parent be37f77 commit 0e0f721

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

source/util/convert_to_iso_string.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@ import { Moment } from "moment";
22
import type dayjs from "dayjs";
33

44
/**
5-
* Checks if string is in ISO 6801 format.
5+
* Checks if string is in ISO 6801 format including time and optionally
6+
* milliseconds and timezone.
7+
*
8+
* Matches:
9+
* - YYYY-MM-DDThh:mm:ss
10+
* - YYYY-MM-DDThh:mm:ssTZD
11+
* - YYYY-MM-DDThh:mm:ss.sTZD
612
*/
713
function isIsoDate(str: string) {
8-
return /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/.test(
14+
return /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i.test(
915
str,
1016
);
1117
}

test/convert_to_iso_string.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,30 @@ describe("convertToIsoString", () => {
4141
expect(converted).toEqual(isoDate);
4242
});
4343

44+
it.each([
45+
"2023-01-01T00:00:00",
46+
"2023-01-01T00:00:00Z",
47+
"2023-01-01T00:00:00z",
48+
"2023-01-01T00:00:00.000Z",
49+
"2023-01-01T00:00:00.000z",
50+
"2023-01-01T00:00:00.000+00:00",
51+
"2023-01-01T00:00:00.000+01:00",
52+
"2023-01-01T00:00:00+01:00",
53+
"2023-01-01T00:00:00.000-01:00",
54+
])("should allow for variations in ms and timezone: %s", (validDate) => {
55+
const converted = convertToIsoString(validDate);
56+
const dayjsConverted = dayjs(validDate).toISOString();
57+
expect(converted).toEqual(dayjsConverted);
58+
});
59+
60+
it.each(["2023", "2023-01", "2023-01-01", "2023-W01-01", "2023-01-01T00:00"])(
61+
"should not match incomplete date-times",
62+
(invalidDate) => {
63+
const converted = convertToIsoString(invalidDate);
64+
expect(converted).toEqual(null);
65+
},
66+
);
67+
4468
it.each([
4569
"hello world",
4670
"202f",

0 commit comments

Comments
 (0)