Skip to content

Commit

Permalink
Add duration fromISO negative millisecond handling (#887)
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-overton committed May 8, 2021
1 parent c34afb1 commit da04179
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/impl/regexParser.js
Expand Up @@ -140,8 +140,10 @@ function extractISODuration(match) {
] = match;

const hasNegativePrefix = s[0] === "-";
const negativeSeconds = secondStr && secondStr[0] === "-";

const maybeNegate = num => (num && hasNegativePrefix ? -num : num);
const maybeNegate = (num, force = false) =>
num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;

return [
{
Expand All @@ -151,8 +153,8 @@ function extractISODuration(match) {
days: maybeNegate(parseInteger(dayStr)),
hours: maybeNegate(parseInteger(hourStr)),
minutes: maybeNegate(parseInteger(minuteStr)),
seconds: maybeNegate(parseInteger(secondStr)),
milliseconds: maybeNegate(parseMillis(millisecondsStr))
seconds: maybeNegate(parseInteger(secondStr), secondStr === "-0"),
milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
}
];
}
Expand Down
4 changes: 4 additions & 0 deletions test/duration/parse.test.js
Expand Up @@ -31,6 +31,10 @@ test("Duration.fromISO can parse mixed or negative durations", () => {
check("-P5Y3M", { years: -5, months: -3 });
check("-P-5Y-3M", { years: 5, months: 3 });
check("-P-1W1DT13H-23M34S", { weeks: 1, days: -1, hours: -13, minutes: 23, seconds: -34 });
check("PT-1.5S", { seconds: -1, milliseconds: -500 });
check("PT-0.5S", { seconds: 0, milliseconds: -500 });
check("PT1.5S", { seconds: 1, milliseconds: 500 });
check("PT0.5S", { seconds: 0, milliseconds: 500 });
});

test("Duration.fromISO can parse fractions of seconds", () => {
Expand Down

0 comments on commit da04179

Please sign in to comment.