From f7f11b78200cb7bbabcff7fd50babb3e4de486e1 Mon Sep 17 00:00:00 2001 From: Dmytro Gokun Date: Wed, 23 Oct 2019 20:01:40 +0300 Subject: [PATCH] Allow `parseJSON` to accept strings without a trailing 'Z' symbold and with up to 6 digits in the milliseconds field (#1463) --- src/parseJSON/index.js | 5 ++++- src/parseJSON/test.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/parseJSON/index.js b/src/parseJSON/index.js index 0a7c77be64..dae535368e 100644 --- a/src/parseJSON/index.js +++ b/src/parseJSON/index.js @@ -17,6 +17,9 @@ import toDate from '../toDate/index.js' * - `2000-03-15T05:20:10Z`: Without milliseconds * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon + * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol + * - `2000-03-15T05:20:10.134566`: Up to 6 digits in milliseconds field. Only first 3 are taken into account + * since JS does now allow fractional milliseconds * * For convenience and ease of use these other input types are also supported * via [toDate]{@link https://date-fns.org/docs/toDate}: @@ -39,7 +42,7 @@ export default function parseJSON(argument) { if (typeof argument === 'string') { var parts = argument.match( - /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?(?:Z|\+00:?00)/ + /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3})\d{0,3})?(?:Z|\+00:?00)?/ ) if (parts) { return new Date( diff --git a/src/parseJSON/test.js b/src/parseJSON/test.js index a0d6242857..822005b1cf 100644 --- a/src/parseJSON/test.js +++ b/src/parseJSON/test.js @@ -32,6 +32,20 @@ describe('parseJSON', function() { assert.equal(parsedDate.toISOString(), expectedDate) }) + it('parses a fully formed ISO date without Z', () => { + const date = '2000-03-15T05:20:10.123' + const expectedDate = '2000-03-15T05:20:10.123Z' + const parsedDate = parseJSON(date) + assert.equal(parsedDate.toISOString(), expectedDate) + }) + + it('parses a fully formed ISO date without Z and with 6-digit millisecond part', () => { + const date = '2000-03-15T05:20:10.123456' + const expectedDate = '2000-03-15T05:20:10.123Z' + const parsedDate = parseJSON(date) + assert.equal(parsedDate.toISOString(), expectedDate) + }) + it('clones a date object', () => { const date = new Date(2000, 2, 15, 5, 20, 10, 20) const parsedDate = parseJSON(date)