From 70c123990dcc6bd479fa2b5d7f9985127872a826 Mon Sep 17 00:00:00 2001 From: dyoshikawa <34151621+dyoshikawa@users.noreply.github.com> Date: Wed, 29 Jul 2020 11:42:13 +0900 Subject: [PATCH] fix: Update Regex to parse 'YYYY' correctly (#969) --- src/constant.js | 2 +- src/index.js | 6 ++++-- test/plugin/utc.test.js | 9 +++++++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/constant.js b/src/constant.js index 5dbff805..b253c74e 100644 --- a/src/constant.js +++ b/src/constant.js @@ -26,5 +26,5 @@ export const FORMAT_DEFAULT = 'YYYY-MM-DDTHH:mm:ssZ' export const INVALID_DATE_STRING = 'Invalid Date' // regex -export const REGEX_PARSE = /^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/ +export const REGEX_PARSE = /^(\d{4})-?(\d{1,2})?-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/ export const REGEX_FORMAT = /\[([^\]]+)]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g diff --git a/src/index.js b/src/index.js index abda8c9e..9a669e6b 100644 --- a/src/index.js +++ b/src/index.js @@ -59,11 +59,13 @@ const parseDate = (cfg) => { if (typeof date === 'string' && !/Z$/i.test(date)) { const d = date.match(C.REGEX_PARSE) if (d) { + const m = d[2] - 1 || 0 if (utc) { - return new Date(Date.UTC(d[1], d[2] - 1, d[3] + return new Date(Date.UTC(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0)) } - return new Date(d[1], d[2] - 1, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0) + return new Date(d[1], m, d[3] + || 1, d[4] || 0, d[5] || 0, d[6] || 0, d[7] || 0) } } diff --git a/test/plugin/utc.test.js b/test/plugin/utc.test.js index 9a90adca..dc290de1 100644 --- a/test/plugin/utc.test.js +++ b/test/plugin/utc.test.js @@ -56,12 +56,17 @@ describe('Parse UTC ', () => { it('Parse date string without timezome', () => { const d = '2018-09-06' - const d2 = '2018-09' expect(dayjs.utc(d).format()).toEqual(moment.utc(d).format()) expect(dayjs.utc(d).format()).toEqual('2018-09-06T00:00:00Z') + expect(dayjs(d).utc().format()).toEqual(moment(d).utc().format()) + const d2 = '2018-09' expect(dayjs.utc(d2).format()).toEqual(moment.utc(d2).format()) expect(dayjs.utc(d2).format()).toEqual('2018-09-01T00:00:00Z') - expect(dayjs(d).utc().format()).toEqual(moment(d).utc().format()) + expect(dayjs(d2).utc().format()).toEqual(moment(d2).utc().format()) + const d3 = '2018' + expect(dayjs.utc(d3).format()).toEqual(moment.utc(d3).format()) + expect(dayjs.utc(d3).format()).toEqual('2018-01-01T00:00:00Z') + expect(dayjs(d3).utc().format()).toEqual(moment(d3).utc().format()) }) it('creating with utc with timezone', () => {