Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/utils/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import { toInteger } from './number'

// --- Constants ---

const RX_DATE = /^\d+-\d+-\d+$/
// Loose YYYY-MM-DD matching, ignores any appended time inforation
// Matches '1999-12-20', '1999-1-1', '1999-01-20T22:51:49.118Z', '1999-01-02 13:00:00'
const RX_DATE = /^\d+-\d\d?-\d\d?(?:\s|T|$)/

// Used to split off the date parts of the YYYY-MM-DD string
const RX_DATE_SPLIT = /-|\s|T/

// --- Date utility methods ---

Expand All @@ -16,7 +21,7 @@ export const createDate = (...args) => new Date(...args)
// Parse a date sting, or Date object, into a Date object (with no time information)
export const parseYMD = date => {
if (isString(date) && RX_DATE.test(date.trim())) {
const [year, month, day] = date.split('-').map(toInteger)
const [year, month, day] = date.split(RX_DATE_SPLIT).map(v => toInteger(v, 1))
return createDate(year, month - 1, day)
} else if (isDate(date)) {
return createDate(date.getFullYear(), date.getMonth(), date.getDate())
Expand Down
8 changes: 8 additions & 0 deletions src/utils/date.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,14 @@ describe('utils/date', () => {
it('parseYMD works', async () => {
const date1 = parseYMD('2020-01-15')
const date2 = new Date(2020, 0, 15)
const date3 = parseYMD('2020-01-15T23:16:56.131Z')
const date4 = parseYMD('2020-01-15 23:16:56')

expect(date1.toISOString()).toEqual(date2.toISOString())
expect(date1.toISOString()).toEqual(date3.toISOString())
expect(date1.toISOString()).toEqual(date4.toISOString())
expect(parseYMD('yyyy-mm-dd')).toEqual(null)
expect(parseYMD('2020-01-15XYZ')).toEqual(null)
})

it('formatYMD works', async () => {
Expand All @@ -28,6 +33,9 @@ describe('utils/date', () => {
expect(formatYMD('2020-01-32')).toEqual('2020-02-01')
expect(formatYMD('adsadsad')).toEqual(null)
expect(formatYMD('x2020-01-15')).toEqual(null)
expect(formatYMD('2020-01-15x')).toEqual(null)
expect(formatYMD('2020-01-15T23:16:56.131Z')).toEqual('2020-01-15')
expect(formatYMD('2020-01-15 23:16:56')).toEqual('2020-01-15')
})

it('datesEqual works', async () => {
Expand Down