From fd89a294dcab017dbbe7000bce613b0d4ed60f96 Mon Sep 17 00:00:00 2001 From: Jamie Davies Date: Mon, 4 Jul 2022 11:47:18 +0100 Subject: [PATCH] fix: Improve spanner.date handling of years before 1000AD (#1654) * fix: Improve spanner.date handling of years before 1000AD * fix: linting and code comment for date return --- src/codec.ts | 23 +++++++++-------------- test/codec.ts | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/codec.ts b/src/codec.ts index fe6a3db91..58f6c20bc 100644 --- a/src/codec.ts +++ b/src/codec.ts @@ -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' + )}`; } } diff --git a/test/codec.ts b/test/codec.ts index 43dec97e8..d5962e053 100644 --- a/test/codec.ts +++ b/test/codec.ts @@ -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(); @@ -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'); + }); }); });