diff --git a/src/plugin/duration/index.js b/src/plugin/duration/index.js index 48ceadd8..50f66048 100644 --- a/src/plugin/duration/index.js +++ b/src/plugin/duration/index.js @@ -179,11 +179,13 @@ export default (option, Dayjs, dayjs) => { dayjs.isDuration = isDuration const oldAdd = Dayjs.prototype.add - Dayjs.prototype.add = function (addition, units) { - if (isDuration(addition)) { - addition = addition.asMilliseconds() - units = 'ms' - } - return oldAdd.bind(this)(addition, units) + const oldSubtract = Dayjs.prototype.subtract + Dayjs.prototype.add = function (value, unit) { + if (isDuration(value)) value = value.asMilliseconds() + return oldAdd.bind(this)(value, unit) + } + Dayjs.prototype.subtract = function (value, unit) { + if (isDuration(value)) value = value.asMilliseconds() + return oldSubtract.bind(this)(value, unit) } } diff --git a/test/plugin/duration.test.js b/test/plugin/duration.test.js index a85accf3..5e544765 100644 --- a/test/plugin/duration.test.js +++ b/test/plugin/duration.test.js @@ -139,7 +139,7 @@ describe('Add', () => { expect(a.add({ days: 5 }).days()).toBe(6) }) -describe('Add duration', () => { +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') @@ -151,6 +151,11 @@ describe('Subtract', () => { expect(a.subtract(b).days()).toBe(1) }) +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') +}) describe('Seconds', () => { expect(dayjs.duration(500).seconds()).toBe(0) diff --git a/types/index.d.ts b/types/index.d.ts index e3e62495..fcc9f4c4 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -226,7 +226,7 @@ declare namespace dayjs { * * Docs: https://day.js.org/docs/en/manipulate/add */ - add(value: number, unit: OpUnitType): Dayjs + add(value: number, unit?: OpUnitType): Dayjs /** * Returns a cloned Day.js object with a specified amount of time subtracted. * ``` @@ -236,7 +236,7 @@ declare namespace dayjs { * * Docs: https://day.js.org/docs/en/manipulate/subtract */ - subtract(value: number, unit: OpUnitType): Dayjs + subtract(value: number, unit?: OpUnitType): Dayjs /** * Returns a cloned Day.js object and set it to the start of a unit of time. * ``` diff --git a/types/plugin/duration.d.ts b/types/plugin/duration.d.ts index 3f679152..c09dc9f0 100644 --- a/types/plugin/duration.d.ts +++ b/types/plugin/duration.d.ts @@ -56,6 +56,11 @@ declare namespace plugin { } declare module 'dayjs' { + interface Dayjs { + add(value: plugin.Duration): Dayjs + subtract(value: plugin.Duration): Dayjs + } + export function duration(input?: plugin.DurationInputType , unit?: string): plugin.Duration export function isDuration(d: any): d is plugin.Duration }