duration plugin: leading sign of an ISO 8601 duration is ignored ("-P1D" parses as +1 day)
Version: dayjs 1.11.23, dayjs/plugin/duration, Node 22
dayjs.duration('-P1D') returns a positive duration. The parse regex has a capture group for a leading - or +, but the sign is never applied.
Reproduction
const dayjs = require('dayjs');
dayjs.extend(require('dayjs/plugin/duration'));
for (const s of ['P1D', '+P1D', '-P1D', '-PT1H', '-P1DT2H', '-P1Y', 'P-1D']) {
const d = dayjs.duration(s);
console.log(s.padEnd(8), d.asMilliseconds(), d.toISOString());
}
// P1D 86400000 P1D
// +P1D 86400000 P1D
// -P1D 86400000 P1D <- expected -86400000 / -P1D
// -PT1H 3600000 PT1H <- expected -3600000 / -PT1H
// -P1DT2H 93600000 P1DT2H <- expected negative
// -P1Y 31536000000 P1Y <- expected negative
// P-1D -86400000 -P1D (works, only because the sign is inside the component)
This also breaks round trips: dayjs.duration(-86400000).toISOString() gives -P1D, and dayjs.duration('-P1D') on that string gives back the opposite sign.
Cause
In src/plugin/duration/index.js:
const durationRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?.../
...
const d = input.match(durationRegex)
if (d) {
const [y, M, w, days, h, m, s] = d.slice(2) // d[1] (the sign) is dropped
The sign in d[1] is matched and then discarded with slice(2).
Expected
If d[1] === '-', negate every component (or the resulting millisecond value), matching what toISOString() produces for negative durations. ISO 8601-2 / java.time.Duration.parse("-PT1H") / Temporal all treat a leading - as negating the whole duration.
I'll take this. Planning to apply the leading ISO 8601 sign (d[1]) when parsing duration strings so -P1D / -PT1H negate the whole duration, matching toISOString() and existing in-component signs like P-1D.