Skip to content

Commit

Permalink
fix(std/datetime): partsToDate (denoland#8553)
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxintang authored and kitsonk committed Dec 18, 2020
1 parent a494942 commit 18176bc
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
25 changes: 24 additions & 1 deletion std/datetime/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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);
}
}
3 changes: 2 additions & 1 deletion std/datetime/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
4 changes: 4 additions & 0 deletions std/datetime/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 18176bc

Please sign in to comment.