Skip to content

Commit

Permalink
fix: Improve spanner.date handling of years before 1000AD (#1654)
Browse files Browse the repository at this point in the history
* fix: Improve spanner.date handling of years before 1000AD

* fix: linting and code comment for date return
  • Loading branch information
viralpickaxe authored Jul 4, 2022
1 parent 781cdac commit fd89a29
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
23 changes: 9 additions & 14 deletions src/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,24 +92,19 @@ export class SpannerDate extends Date {
}
/**
* Returns the date in ISO date format.
* `YYYY-[M]M-[D]D`
* `YYYY-MM-DD`
*
* @returns {string}
*/
toJSON(): string {
const year = this.getFullYear();
let month = (this.getMonth() + 1).toString();
let date = this.getDate().toString();

if (month.length === 1) {
month = `0${month}`;
}

if (date.length === 1) {
date = `0${date}`;
}

return `${year}-${month}-${date}`;
const year = this.getFullYear().toString();
const month = (this.getMonth() + 1).toString();
const date = this.getDate().toString();

return `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${date.padStart(
2,
'0'
)}`;
}
}

Expand Down
25 changes: 25 additions & 0 deletions test/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ describe('codec', () => {
assert.strictEqual(json, '1986-03-22');
});

it('should accept dates before 1000AD', () => {
const date = new codec.SpannerDate('2-25-985');
const json = date.toJSON();

assert.strictEqual(json, '0985-02-25');
});

it('should default to the current local date', () => {
const date = new codec.SpannerDate();
const today = new Date();
Expand Down Expand Up @@ -118,6 +125,24 @@ describe('codec', () => {
const json = date.toJSON();
assert.strictEqual(json, '1999-12-03');
});

it('should pad single digit years', () => {
(date.getFullYear as sinon.SinonStub).returns(5);
const json = date.toJSON();
assert.strictEqual(json, '0005-12-31');
});

it('should pad double digit years', () => {
(date.getFullYear as sinon.SinonStub).returns(52);
const json = date.toJSON();
assert.strictEqual(json, '0052-12-31');
});

it('should pad triple digit years', () => {
(date.getFullYear as sinon.SinonStub).returns(954);
const json = date.toJSON();
assert.strictEqual(json, '0954-12-31');
});
});
});

Expand Down

0 comments on commit fd89a29

Please sign in to comment.