Skip to content

Commit

Permalink
fix: Fix set Month Year error in last day of the month
Browse files Browse the repository at this point in the history
  • Loading branch information
allmoviestvshowslistsfilmography28 authored and iamkun committed Mar 29, 2019
1 parent 35cf565 commit 96c9444
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions test/get-set.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down

0 comments on commit 96c9444

Please sign in to comment.