Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Improve spanner.date handling of years before 1000AD #1654

Merged
merged 2 commits into from
Jul 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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