From cd907340d5fe8b52905d43b41a02308fb809f8f7 Mon Sep 17 00:00:00 2001 From: Edward Faulkner Date: Tue, 15 Mar 2022 00:30:47 -0400 Subject: [PATCH] Make date serializer respect ISO 8601 The default date serializer looks like it intends to follow ISO 8601, and its test says "#serialize returns a date in YYYY-MM-DD form". But it doesn't always emit YYYY-MM-DD form, because it doesn't insert leading zeros for single digit months and days. This results in dates that aren't strictly conformant to ISO 8601. This change adds the necessary padding. This is probably a breaking change. --- packages/@orbit/serializers/src/date-serializer.ts | 5 ++++- packages/@orbit/serializers/test/date-serializer-test.ts | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/@orbit/serializers/src/date-serializer.ts b/packages/@orbit/serializers/src/date-serializer.ts index 61931f01..64190677 100644 --- a/packages/@orbit/serializers/src/date-serializer.ts +++ b/packages/@orbit/serializers/src/date-serializer.ts @@ -2,7 +2,10 @@ import { BaseSerializer } from './base-serializer'; export class DateSerializer extends BaseSerializer { serialize(arg: Date): string { - return `${arg.getFullYear()}-${arg.getMonth() + 1}-${arg.getDate()}`; + let YYYY = arg.getFullYear().toString().padStart(4, '0'); + let MM = (arg.getMonth() + 1).toString().padStart(2, '0'); + let DD = arg.getDate().toString().padStart(2, '0'); + return `${YYYY}-${MM}-${DD}`; } deserialize(arg: string): Date { diff --git a/packages/@orbit/serializers/test/date-serializer-test.ts b/packages/@orbit/serializers/test/date-serializer-test.ts index 97d9a85b..d79a9ba9 100644 --- a/packages/@orbit/serializers/test/date-serializer-test.ts +++ b/packages/@orbit/serializers/test/date-serializer-test.ts @@ -13,6 +13,10 @@ module('DateSerializer', function (hooks) { assert.equal(serializer.serialize(new Date(2017, 11, 31)), '2017-12-31'); }); + test('#serialize returns a date in YYYY-MM-DD form when leading zeros are needed', function (assert) { + assert.equal(serializer.serialize(new Date(2017, 4, 31)), '2017-05-31'); + }); + test('#deserialize returns a Date', function (assert) { assert.equal( serializer.deserialize('2017-12-31')?.toISOString(),