From 96c9444ccdea422a3c5d094e796e3b61963c2c99 Mon Sep 17 00:00:00 2001 From: iamkun <5992643+manre57@users.noreply.github.com> Date: Fri, 29 Mar 2019 17:59:55 +0800 Subject: [PATCH] fix: Fix set Month Year error in last day of the month --- src/index.js | 16 ++++++++-------- test/get-set.test.js | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/index.js b/src/index.js index ffdbe96..780ad3b 100644 --- a/src/index.js +++ b/src/index.js @@ -218,7 +218,12 @@ class Dayjs { }[unit] const arg = unit === C.D ? this.$D + (int - this.$W) : int - if (this.$d[name]) this.$d[name](arg) + if (unit === C.M || unit === C.Y) { + const date = this.clone().set(C.DATE, 1) + date.$d[name](arg) + date.init() + this.$d = date.set(C.DATE, Math.min(this.$D, date.daysInMonth())).toDate() + } else if (name) this.$d[name](arg) this.init() return this @@ -231,21 +236,16 @@ class Dayjs { add(number, units) { number = Number(number) // eslint-disable-line no-param-reassign const unit = Utils.p(units) - const instanceFactory = (u, n) => { - // clone is for badMutable plugin - const date = this.clone().set(C.DATE, 1).set(u, n + number) - return date.set(C.DATE, Math.min(this.$D, date.daysInMonth())) - } const instanceFactorySet = (n) => { const date = new Date(this.$d) date.setDate(date.getDate() + (n * number)) return Utils.w(date, this) } if (unit === C.M) { - return instanceFactory(C.M, this.$M) + return this.set(C.M, this.$M + number) } if (unit === C.Y) { - return instanceFactory(C.Y, this.$y) + return this.set(C.Y, this.$y + number) } if (unit === C.D) { return instanceFactorySet(1) diff --git a/test/get-set.test.js b/test/get-set.test.js index 7587915..cf604df 100644 --- a/test/get-set.test.js +++ b/test/get-set.test.js @@ -90,6 +90,21 @@ it('Set Millisecond', () => { expect(dayjs().set('millisecond', 999).valueOf()).toBe(moment().set('millisecond', 999).valueOf()) }) +it('Set Month and Year in last day of month', () => { + // 2011-07-31 -> 2011-02-28 + const origin = dayjs('2011-07-31T14:48:00.000Z') + const setMonth = origin.set('month', 1) + expect(setMonth.month()).toBe(1) + expect(origin.date()).toBe(31) + expect(setMonth.date()).toBe(28) + // 2000-02-29 -> 2001-02-28 + const origin2 = dayjs('2000-02-29T14:48:00.000Z') + const setYear = origin2.set('year', 2001) + expect(setYear.month()).toBe(1) + expect(origin2.date()).toBe(29) + expect(setYear.date()).toBe(28) +}) + it('Set Unknown String', () => { const newDate = dayjs().set('Unknown String', 1) expect(newDate.valueOf())