Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/plugin/duration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,18 @@ class Duration {
.fromNow(!withSuffix)
}

asObject() {
return {
years: this.years(),
months: this.months(),
days: this.days(),
hours: this.hours(),
minutes: this.minutes(),
seconds: this.seconds(),
milliseconds: this.milliseconds()
}
}

valueOf() {
return this.asMilliseconds()
}
Expand Down
29 changes: 29 additions & 0 deletions test/plugin/duration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,32 @@ describe('Format', () => {
.toBe('2/02.0002TEST9:09:6:06:8:08:5:05:1:01:010')
})
})

it('duration.asObject()', () => {
const d = dayjs.duration({
years: 1,
months: 2,
days: 3,
hours: 4,
minutes: 5,
seconds: 6,
milliseconds: 7
})

const expectedObject = {
years: 1,
months: 2,
days: 3,
hours: 4,
minutes: 5,
seconds: 6,
milliseconds: 7
}

expect(d.asObject()).toEqual(expectedObject)

// Test from milliseconds (as suggested in issue)
const dFromMs = dayjs.duration(1000 * 60 * 60) // 1 hour
expect(dFromMs.asObject().hours).toBe(1)
expect(dFromMs.asObject().minutes).toBe(0)
})
12 changes: 12 additions & 0 deletions types/plugin/duration.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,25 @@ declare namespace plugin {
& ((ISO_8601: string) => Duration)
type AddDurationType = CreateDurationType & ((duration: Duration) => Duration)

interface DurationAsObject {
years: number;
months: number;
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
}

interface Duration {
new (input: string | number | object, unit?: string, locale?: string): Duration

clone(): Duration

humanize(withSuffix?: boolean): string

asObject(): DurationAsObject

milliseconds(): number
asMilliseconds(): number

Expand Down