Skip to content

Commit

Permalink
fix: update Duration plugin add/subtract take into account days in mo…
Browse files Browse the repository at this point in the history
…nth (#2337)
  • Loading branch information
alexander-ulaev authored Jun 24, 2023
1 parent 3c2c6ee commit 3b1060f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/plugin/duration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,15 @@ class Duration {
asYears() { return this.as('years') }
}

const manipulateDuration = (date, duration, k) =>
date.add(duration.years() * k, 'y')
.add(duration.months() * k, 'M')
.add(duration.days() * k, 'd')
.add(duration.hours() * k, 'h')
.add(duration.minutes() * k, 'm')
.add(duration.seconds() * k, 's')
.add(duration.milliseconds() * k, 'ms')

export default (option, Dayjs, dayjs) => {
$d = dayjs
$u = dayjs().$utils()
Expand All @@ -268,12 +277,20 @@ export default (option, Dayjs, dayjs) => {

const oldAdd = Dayjs.prototype.add
const oldSubtract = Dayjs.prototype.subtract

Dayjs.prototype.add = function (value, unit) {
if (isDuration(value)) value = value.asMilliseconds()
if (isDuration(value)) {
return manipulateDuration(this, value, 1)
}

return oldAdd.bind(this)(value, unit)
}

Dayjs.prototype.subtract = function (value, unit) {
if (isDuration(value)) value = value.asMilliseconds()
if (isDuration(value)) {
return manipulateDuration(this, value, -1)
}

return oldSubtract.bind(this)(value, unit)
}
}
8 changes: 8 additions & 0 deletions test/plugin/duration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ test('Add duration', () => {
const a = dayjs('2020-10-01')
const days = dayjs.duration(2, 'days')
expect(a.add(days).format('YYYY-MM-DD')).toBe('2020-10-03')

const b = dayjs('2023-02-01 00:00:00')
const p = dayjs.duration('P1Y1M1DT1H1M1S')
expect(b.add(p).format('YYYY-MM-DD HH:mm:ss')).toBe('2024-03-02 01:01:01')
})

describe('Subtract', () => {
Expand All @@ -194,6 +198,10 @@ test('Subtract duration', () => {
const a = dayjs('2020-10-20')
const days = dayjs.duration(2, 'days')
expect(a.subtract(days).format('YYYY-MM-DD')).toBe('2020-10-18')

const b = dayjs('2023-03-02 02:02:02')
const p = dayjs.duration('P1Y1M1DT1H1M1S')
expect(b.subtract(p).format('YYYY-MM-DD HH:mm:ss')).toBe('2022-02-01 01:01:01')
})

describe('Seconds', () => {
Expand Down

0 comments on commit 3b1060f

Please sign in to comment.