Skip to content

Commit d058f4a

Browse files
committed
fix: Fix set Month Year error in last day of the month
1 parent d1b9cf9 commit d058f4a

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

src/index.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,12 @@ class Dayjs {
218218
}[unit]
219219
const arg = unit === C.D ? this.$D + (int - this.$W) : int
220220

221-
if (this.$d[name]) this.$d[name](arg)
221+
if (unit === C.M || unit === C.Y) {
222+
const date = this.clone().set(C.DATE, 1)
223+
date.$d[name](arg)
224+
date.init()
225+
this.$d = date.set(C.DATE, Math.min(this.$D, date.daysInMonth())).toDate()
226+
} else if (name) this.$d[name](arg)
222227

223228
this.init()
224229
return this
@@ -231,21 +236,16 @@ class Dayjs {
231236
add(number, units) {
232237
number = Number(number) // eslint-disable-line no-param-reassign
233238
const unit = Utils.p(units)
234-
const instanceFactory = (u, n) => {
235-
// clone is for badMutable plugin
236-
const date = this.clone().set(C.DATE, 1).set(u, n + number)
237-
return date.set(C.DATE, Math.min(this.$D, date.daysInMonth()))
238-
}
239239
const instanceFactorySet = (n) => {
240240
const date = new Date(this.$d)
241241
date.setDate(date.getDate() + (n * number))
242242
return Utils.w(date, this)
243243
}
244244
if (unit === C.M) {
245-
return instanceFactory(C.M, this.$M)
245+
return this.set(C.M, this.$M + number)
246246
}
247247
if (unit === C.Y) {
248-
return instanceFactory(C.Y, this.$y)
248+
return this.set(C.Y, this.$y + number)
249249
}
250250
if (unit === C.D) {
251251
return instanceFactorySet(1)

test/get-set.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,21 @@ it('Set Millisecond', () => {
9090
expect(dayjs().set('millisecond', 999).valueOf()).toBe(moment().set('millisecond', 999).valueOf())
9191
})
9292

93+
it('Set Month and Year in last day of month', () => {
94+
// 2011-07-31 -> 2011-02-28
95+
const origin = dayjs('2011-07-31T14:48:00.000Z')
96+
const setMonth = origin.set('month', 1)
97+
expect(setMonth.month()).toBe(1)
98+
expect(origin.date()).toBe(31)
99+
expect(setMonth.date()).toBe(28)
100+
// 2000-02-29 -> 2001-02-28
101+
const origin2 = dayjs('2000-02-29T14:48:00.000Z')
102+
const setYear = origin2.set('year', 2001)
103+
expect(setYear.month()).toBe(1)
104+
expect(origin2.date()).toBe(29)
105+
expect(setYear.date()).toBe(28)
106+
})
107+
93108
it('Set Unknown String', () => {
94109
const newDate = dayjs().set('Unknown String', 1)
95110
expect(newDate.valueOf())

0 commit comments

Comments
 (0)