API reference › @evolu/common › Type › DateIsoFromRfc3339
const DateIsoFromRfc3339: transform(
"DateIsoFromRfc3339",
String,
DateIso,
{
from: (value: string): Result<string, DateIsoFromRfc3339Error> => {
const match =
/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.(\d{1,3})0*)?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.exec(
value,
);
if (match !== null) {
const [, year, month, day, fraction = "", offset] = match;
if (
globalThis.Number(day) <=
daysInMonth(globalThis.Number(year), globalThis.Number(month))
) {
// The ECMAScript Date Time String Format is parsed the same way in
// every engine, unlike other date-time text.
return ok(
new globalThis.Date(
`${value.slice(0, 19)}.${fraction.padEnd(3, "0")}${offset}`,
).toISOString(),
);
}
}
return err({ type: "DateIsoFromRfc3339", value });
},
to: identity,
},
formatDateIsoFromRfc3339Error,
);
Defined in: packages/common/src/Type.ts:6274
Transforms an RFC 3339 date-time string into a canonical DateIso.
Accepts the date-time of RFC 3339 section
5.6 with an uppercase
T and Z, required seconds, an optional fraction whose digits after the
third are zeros, as in .123000, and an offset of Z or ±HH:MM, where
-00:00 means UTC. The date must exist, as in PlainDateIso. Leap
seconds, 24:00, a space separator, the offset forms ±HH and ±HHMM, and
a nonzero fraction digit after the third are rejected rather than rolled over
or rounded; truncate extra fraction digits explicitly.
Decoding converts the offset to UTC, so it does not depend on the local time
zone. An offset can move the moment outside the DateIso range, as in
0000-01-01T00:00:00+01:00, which is a DateIso error. Encoding returns the
DateIso text, which is itself an RFC 3339 date-time.
Example
import {
assertEqual,
assertErr,
assertOk,
DateIsoFromRfc3339,
} from "@evolu/common";
assertOk(
DateIsoFromRfc3339.fromUnknown("2024-01-01T12:00:00Z"),
"2024-01-01T12:00:00.000Z",
);
assertOk(
DateIsoFromRfc3339.fromUnknown("2024-01-01T01:30:00.5+02:00"),
"2023-12-31T23:30:00.500Z",
);
const value = "2024-01-01 12:00:00Z";
const invalid = DateIsoFromRfc3339.fromUnknown(value);
assertErr(invalid, { type: "DateIsoFromRfc3339", value });
assertEqual(
DateIsoFromRfc3339.formatError(invalid.error),
'The value "2024-01-01 12:00:00Z" is not a supported RFC 3339 date-time. Use a value such as "2024-01-01T12:00:00Z".',
);