Skip to content

Commit

Permalink
fix: update date utils to parse year correctly for years 1-999 (#9236)
Browse files Browse the repository at this point in the history
* fix: update date utils to parse year correctly for years 1-999

Closes: #9230

* fix: commit change to date utils

* fix: default total length to 2
  • Loading branch information
a88zach committed Aug 24, 2022
1 parent bb07244 commit 72a0147
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/util/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class DateUtils {
static mixedDateToDateString(value: string | Date): string {
if (value instanceof Date)
return (
this.formatZerolessValue(value.getFullYear()) +
this.formatZerolessValue(value.getFullYear(), 4) +
"-" +
this.formatZerolessValue(value.getMonth() + 1) +
"-" +
Expand Down Expand Up @@ -151,7 +151,7 @@ export class DateUtils {
}
if (value instanceof Date) {
let finalValue =
this.formatZerolessValue(value.getFullYear()) +
this.formatZerolessValue(value.getFullYear(), 4) +
"-" +
this.formatZerolessValue(value.getMonth() + 1) +
"-" +
Expand Down Expand Up @@ -183,7 +183,7 @@ export class DateUtils {
}
if (value instanceof Date) {
return (
this.formatZerolessValue(value.getUTCFullYear()) +
this.formatZerolessValue(value.getUTCFullYear(), 4) +
"-" +
this.formatZerolessValue(value.getUTCMonth() + 1) +
"-" +
Expand Down Expand Up @@ -258,12 +258,12 @@ export class DateUtils {
// -------------------------------------------------------------------------

/**
* Formats given number to "0x" format, e.g. if it is 1 then it will return "01".
* Formats given number to "0x" format, e.g. if the totalLength = 2 and the value is 1 then it will return "01".
*/
private static formatZerolessValue(value: number): string {
if (value < 10) return "0" + value
private static formatZerolessValue(value: number, totalLength = 2): string {
const pad = "0".repeat(totalLength)

return String(value)
return String(`${pad}${value}`).slice(-totalLength)
}

/**
Expand Down
12 changes: 12 additions & 0 deletions test/github-issues/9230/issue-9230.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { DateUtils } from "../../../src/util/DateUtils"
import { expect } from "chai"

describe("github issues > #9230 Incorrect date parsing for year 1-999", () => {
describe("mixedDateToDateString", () => {
it("should format a year less than 1000 with correct 0 padding", () => {
expect(
DateUtils.mixedDateToDateString(new Date("0202-01-01")),
).to.eq("0202-01-01")
})
})
})

0 comments on commit 72a0147

Please sign in to comment.