Skip to content

Commit

Permalink
Make date serializer respect ISO 8601
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ef4 committed Mar 15, 2022
1 parent 3988757 commit cd90734
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/@orbit/serializers/src/date-serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { BaseSerializer } from './base-serializer';

export class DateSerializer extends BaseSerializer<Date, string> {
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 {
Expand Down
4 changes: 4 additions & 0 deletions packages/@orbit/serializers/test/date-serializer-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down

0 comments on commit cd90734

Please sign in to comment.