0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-29 08:58:01 -04:00

fix(std/datetime): partsToDate (#8553)

This commit is contained in:
xiaoxintang 2020-12-12 21:21:48 +08:00 committed by GitHub
parent 93cd9ab0b8
commit 89c14f79a4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 2 deletions

View file

@ -511,6 +511,28 @@ export class DateTimeFormatter {
return parts;
}
/** sort & filter dateTimeFormatPart */
sortDateTimeFormatPart(parts: DateTimeFormatPart[]): DateTimeFormatPart[] {
let result: DateTimeFormatPart[] = [];
const typeArray = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"fractionalSecond",
];
for (const type of typeArray) {
const current = parts.findIndex((el) => el.type === type);
if (current !== -1) {
result = result.concat(parts.splice(current, 1));
}
}
result = result.concat(parts);
return result;
}
partsToDate(parts: DateTimeFormatPart[]): Date {
const date = new Date();
const utc = parts.find(
@ -566,6 +588,7 @@ export class DateTimeFormatter {
parse(string: string): Date {
const parts = this.parseToParts(string);
return this.partsToDate(parts);
const sortParts = this.sortDateTimeFormatPart(parts);
return this.partsToDate(sortParts);
}
}

View file

@ -28,7 +28,8 @@ enum Day {
export function parse(dateString: string, formatString: string): Date {
const formatter = new DateTimeFormatter(formatString);
const parts = formatter.parseToParts(dateString);
return formatter.partsToDate(parts);
const sortParts = formatter.sortDateTimeFormatPart(parts);
return formatter.partsToDate(sortParts);
}
/**

View file

@ -53,6 +53,10 @@ Deno.test({
datetime.parse("03-01-2019", "dd-MM-yyyy"),
new Date(2019, 0, 3),
);
assertEquals(
datetime.parse("31-10-2019", "dd-MM-yyyy"),
new Date(2019, 9, 31),
);
assertEquals(
datetime.parse("2019-01-03", "yyyy-MM-dd"),
new Date(2019, 0, 3),