Skip to content
Merged
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
38 changes: 36 additions & 2 deletions parse.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Times are parsed as UTC if no offset is specified
/**
* _Times are parsed as UTC if no offset is specified_
*/
export class IsoDateParts {
static FULL_DATE_REGEX = /^([+-]\d{6}|\d{4})-?([01]\d)-?([0-3]\d)$/;
static DATETIME_REGEX = /^([+-]\d{6}|\d{4})-?([01]\d)-?([0-3]\d)[Tt ]([0-2]\d(?:[\.\,]\d+)?)(?::?([0-5]\d(?:[\.\,]\d+)?)(?::?([0-5]\d))?(?:[\.\,](\d{1,9}))?)?(Z|[+-][0-2]\d(?::?[0-5]\d)?)?$/;
Expand All @@ -15,6 +17,7 @@ export class IsoDateParts {
};
}

/** @param {RegExpMatchArray} match */
static getByDateTime(
_, // full match
year = "",
Expand All @@ -40,6 +43,7 @@ export class IsoDateParts {
};
}

/** @param {string} str An [RFC 9557](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime#rfc_9557_format)-compatible string */
static getParts(str = "") {
let dateTimeMatch = str.match(this.FULL_DATE_REGEX) ?? str.match(this.DATETIME_REGEX);
if(!dateTimeMatch) {
Expand All @@ -54,6 +58,24 @@ export class IsoDateParts {
}

export class IsoDate {
/** @type {number} */
year;
/** @type {number} */
month;
/** @type {number} */
day;
/** @type {number} */
hours;
/** @type {number} */
minutes;
/** @type {number} */
seconds;
/** @type {number} */
milliseconds;
/** @type {string} */
source;

/** @param {string} str An [RFC 9557](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime#rfc_9557_format)-compatible string */
static parse(str) {
let parts = IsoDateParts.getParts(str);
if(parts) {
Expand All @@ -67,11 +89,22 @@ export class IsoDate {
throw new Error(`Unsupported date format: ${str}`);
}

/**
* @param {object} parts
* @param {number} parts.year
* @param {number} parts.month
* @param {number} parts.day
* @param {number} parts.hours
* @param {number} parts.minutes
* @param {number} parts.seconds
* @param {number} parts.milliseconds
*/
constructor(parts) {
// parts.day, parts.year, parts.month, parts.week
// parts.day, parts.year, parts.month
Object.assign(this, parts);
}

/** @returns {[number, number, number, number, number, number, number]} */
getArgs() {
return [this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds];
}
Expand All @@ -89,6 +122,7 @@ export class IsoDate {
}
}

/** @param {string} str An [RFC 9557](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime#rfc_9557_format)-compatible string */
export function parse(str) {
return IsoDate.parse(str);
}
Loading