Skip to content

Commit

Permalink
Allow parseJSON to accept strings without a trailing 'Z' symbold an…
Browse files Browse the repository at this point in the history
…d with up to 6 digits in the milliseconds field (date-fns#1463)
  • Loading branch information
dmytro-gokun committed Oct 23, 2019
1 parent f6c9517 commit f7f11b7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/parseJSON/index.js
Expand Up @@ -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}:
Expand All @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions src/parseJSON/test.js
Expand Up @@ -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)
Expand Down

0 comments on commit f7f11b7

Please sign in to comment.