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:
parent
93cd9ab0b8
commit
89c14f79a4
3 changed files with 30 additions and 2 deletions
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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),
|
||||
|
|
Loading…
Reference in a new issue