Define type for available date format (#88)

This commit is contained in:
Kwang-in (Dennis) Jung 2019-01-11 14:19:42 +09:00 committed by Ryan Dahl
parent 0e00fe9cd3
commit 3656ab5b99
2 changed files with 22 additions and 5 deletions

View File

@ -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));

View File

@ -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)
);
});