Skip to content

Commit

Permalink
SQL datetime support in parseJSON (#1579)
Browse files Browse the repository at this point in the history
- Added support of space time separator
- Allowed up to 7 digits in milliseconds
  • Loading branch information
marnusw authored and kossnocorp committed Jan 4, 2020
1 parent c0386d6 commit 6887914
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/parseJSON/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import requiredArgs from '../_lib/requiredArgs/index.js'
* - `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
* - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds
* - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting
*
* For convenience and ease of use these other input types are also supported
* via [toDate]{@link https://date-fns.org/docs/toDate}:
Expand All @@ -38,7 +39,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{0,6}))?(?:Z|\+00:?00)?/
/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|\+00:?00)?/
)
if (parts) {
return new Date(
Expand Down
21 changes: 21 additions & 0 deletions src/parseJSON/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,27 @@ describe('parseJSON', function() {
assert.equal(parsedDate.toISOString(), expectedDate)
})

it('parses supported formats with a space time separator instead of a T', () => {
const date = '2000-03-15 05:20:10.123Z'
const expectedDate = '2000-03-15T05:20:10.123Z'
const parsedDate = parseJSON(date)
assert.equal(parsedDate.toISOString(), expectedDate)
})

it('parses the SQL datetime format without milliseconds', () => {
const date = '2000-03-15 05:20:10'
const expectedDate = '2000-03-15T05:20:10.000Z'
const parsedDate = parseJSON(date)
assert.equal(parsedDate.toISOString(), expectedDate)
})

it('parses the SQL datetime format with up to 7 millisecond digits', () => {
const date = '2000-03-15 05:20:10.1234567'
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 6887914

Please sign in to comment.