diff --git a/datetime/mod.ts b/datetime/mod.ts index db66af177..c5e6bf0c4 100644 --- a/datetime/mod.ts +++ b/datetime/mod.ts @@ -1,11 +1,13 @@ +export type DateFormat = "mm-dd-yyyy" | "dd-mm-yyyy" | "yyyy-mm-dd"; + /** * Parse date from string using format string * * @param {string} dateStr - date string - * @param {string} format - format string + * @param {DateFormat} format - format string * @return {Date} Parsed date */ -export function parseDate(dateStr: string, format: string): Date { +export function parseDate(dateStr: string, format: DateFormat): Date { let m, d, y: string; if (format === "mm-dd-yyyy") { @@ -17,19 +19,32 @@ export function parseDate(dateStr: string, format: string): Date { } else if (format === "yyyy-mm-dd") { const datePattern = /^(\d{4})-(\d{2})-(\d{2})$/; [, y, m, d] = datePattern.exec(dateStr); + } else { + throw new Error("Invalid date format!"); } return new Date(Number(y), Number(m) - 1, Number(d)); } +export type DateTimeFormat = + | "mm-dd-yyyy hh:mm" + | "dd-mm-yyyy hh:mm" + | "yyyy-mm-dd hh:mm" + | "hh:mm mm-dd-yyyy" + | "hh:mm dd-mm-yyyy" + | "hh:mm yyyy-mm-dd"; + /** * Parse date & time from string using format string * * @param {string} dateStr - date & time string - * @param {string} format - format string + * @param {DateTimeFormat} format - format string * @return {Date} Parsed date */ -export function parseDateTime(datetimeStr: string, format: string): Date { +export function parseDateTime( + datetimeStr: string, + format: DateTimeFormat +): Date { let m, d, y, ho, mi: string; if (format === "mm-dd-yyyy hh:mm") { @@ -50,6 +65,8 @@ export function parseDateTime(datetimeStr: string, format: string): Date { } else if (format === "hh:mm yyyy-mm-dd") { const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; [, ho, mi, y, m, d] = datePattern.exec(datetimeStr); + } else { + throw new Error("Invalid datetime format!"); } return new Date(Number(y), Number(m) - 1, Number(d), Number(ho), Number(mi)); diff --git a/datetime/test.ts b/datetime/test.ts index d5c1622cc..c0e0f89b1 100644 --- a/datetime/test.ts +++ b/datetime/test.ts @@ -9,7 +9,7 @@ test(function parseDateTime() { }); test(function parseDate() { assertEqual( - datetime.parseDateTime("01-03-2019", "mm-dd-yyyy"), + datetime.parseDate("01-03-2019", "mm-dd-yyyy"), new Date(2019, 1, 3) ); });