diff --git a/src/utils/date.js b/src/utils/date.js index 18ebcb73767..99f6be648f3 100644 --- a/src/utils/date.js +++ b/src/utils/date.js @@ -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 --- @@ -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()) diff --git a/src/utils/date.spec.js b/src/utils/date.spec.js index 0fb1f0d6658..6573e7613ac 100644 --- a/src/utils/date.spec.js +++ b/src/utils/date.spec.js @@ -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 () => { @@ -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 () => {