Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions source/util/convert_to_iso_string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ import { Moment } from "moment";
import type dayjs from "dayjs";

/**
* Checks if string is in ISO 6801 format.
* Checks if string is in ISO 6801 format including time and optionally
* milliseconds and timezone.
*
* Matches:
* - YYYY-MM-DDThh:mm:ss
* - YYYY-MM-DDThh:mm:ssTZD
* - YYYY-MM-DDThh:mm:ss.sTZD
*/
function isIsoDate(str: string) {
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(
return /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i.test(
str,
);
}
Expand Down
24 changes: 24 additions & 0 deletions test/convert_to_iso_string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,30 @@ describe("convertToIsoString", () => {
expect(converted).toEqual(isoDate);
});

it.each([
"2023-01-01T00:00:00",
"2023-01-01T00:00:00Z",
"2023-01-01T00:00:00z",
"2023-01-01T00:00:00.000Z",
"2023-01-01T00:00:00.000z",
"2023-01-01T00:00:00.000+00:00",
"2023-01-01T00:00:00.000+01:00",
"2023-01-01T00:00:00+01:00",
"2023-01-01T00:00:00.000-01:00",
])("should allow for variations in ms and timezone: %s", (validDate) => {
const converted = convertToIsoString(validDate);
const dayjsConverted = dayjs(validDate).toISOString();
expect(converted).toEqual(dayjsConverted);
});

it.each(["2023", "2023-01", "2023-01-01", "2023-W01-01", "2023-01-01T00:00"])(
"should not match incomplete date-times",
(invalidDate) => {
const converted = convertToIsoString(invalidDate);
expect(converted).toEqual(null);
},
);

it.each([
"hello world",
"202f",
Expand Down