iamkun / iamkun/dayjs

format() broken for duration objects (undefined values, wrong format, inconsistent behaviour)

Open
#1,757 3 comments 3 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
Every duration instance I create whether from ISO-string or from object appears to be broken.
The behaviour is also inconsistent between construction from ISO-string or object.

### Case 1 (init leaves undefined values, inconsistent):
```js
dayjs.duration({ seconds: 20 }).format('HH:mm:ss:SSS');
// received: undefined:undefined:20:undefined
// wanted: 00:00:20:000
```
and weirdly:
```js
dayjs.duration('PT20S').format('HH:mm:ss:SSS');
// received: 00:00:20:undefined
// wanted: 00:00:20:000
```

### Case 2 (milliseconds parsing from ISO string):
```js
dayjs.duration({ hours: 1, minutes: 2, seconds: 3, milliseconds: 4 }).format('HH:mm:ss:SSS');
// received: 01:02:03:004
// wanted: 01:02:03:004
```
but from ISO string, parsing is completely broken:
```js
duration = dayjs.duration('PT1H2M3.004S').format('HH:mm:ss:SSS');
// received: 01:02:3.004:undefined
// wanted: 01:02:03:004
```

### Case 3 (overflows not calculated on creation):
```js
dayjs.duration({ seconds: 180 }).format('mm:ss');
// received: undefined:180
// wanted: 03:00
```

### Case 4 (overflow calculation ignores format options)
```js
dayjs.duration({ hours: 23, minutes: 30 }).add(3, 'h').format('HH:mm');
// received: 02:30
// wanted: 26:30
```

## Workaround
Cases 1,2,3 can be worked around by adding nothing (`.add(0,'s')`), like:
```js
// for case 1
dayjs.duration({ seconds: 20 }).add(0,'s').format('HH:mm:ss:SSS');
// received: 00:00:20:000

// for case 2
dayjs.duration('PT1H2M3.004S').add(0,'s').format('HH:mm:ss:SSS');
// received: 01:02:03:004

// for case 3
dayjs.duration({ seconds: 180 }).add(0,'s').format('mm:ss');
// received: 03:00
```

@iamkun Feels like you forgot to call an init function inside the constructor.

**Information**
- Day.js Version 1.10.7
- OS: macOS
- Browser latest and greatest
- Time zone: Europe/Berlin

Contributor guide

Open the contributing guide

Research direction

Reproduce the four duration examples, including ISO-string and object construction, then trace the duration construction, parsing, format, and add entry points. Done means the shown cases produce the expected zero-padded values, normalize overflows on creation, and preserve hour overflows according to the format.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.