Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Duration add/subtract #2337

Merged
merged 3 commits into from
Jun 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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