Skip to content

Commit

Permalink
duration ISO should support fractional seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
icambron committed Mar 12, 2018
1 parent 84273ac commit 5a62569
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
7 changes: 4 additions & 3 deletions src/impl/regexParser.js
Expand Up @@ -108,10 +108,10 @@ function extractIANAZone(match, cursor) {

// ISO duration parsing

const isoDuration = /^P(?:(?:(\d{1,9})Y)?(?:(\d{1,9})M)?(?:(\d{1,9})D)?(?:T(?:(\d{1,9})H)?(?:(\d{1,9})M)?(?:(\d{1,9})S)?)?|(\d{1,9})W)$/;
const isoDuration = /^P(?:(?:(\d{1,9})Y)?(?:(\d{1,9})M)?(?:(\d{1,9})D)?(?:T(?:(\d{1,9})H)?(?:(\d{1,9})M)?(?:(\d{1,9})(?:[.,](\d{1,9}))?S)?)?|(\d{1,9})W)$/;

function extractISODuration(match) {
const [, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, weekStr] = match;
const [, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr, weekStr] = match;

return [ {
years: parseInt(yearStr),
Expand All @@ -120,7 +120,8 @@ function extractISODuration(match) {
days: parseInt(dayStr),
hours: parseInt(hourStr),
minutes: parseInt(minuteStr),
seconds: parseInt(secondStr)
seconds: parseInt(secondStr),
milliseconds: Util.parseMillis(millisecondsStr)
} ];
}

Expand Down
6 changes: 3 additions & 3 deletions src/impl/util.js
Expand Up @@ -82,11 +82,11 @@ export class Util {
}

static parseMillis(fraction) {
if (fraction) {
if (Util.isUndefined(fraction)) {
return NaN;
} else {
const f = parseFloat('0.' + fraction) * 1000;
return Math.floor(f);
} else {
return 0;
}
}

Expand Down
9 changes: 9 additions & 0 deletions test/duration/parse.test.js
Expand Up @@ -18,6 +18,15 @@ test('Duration.fromISO can parse a variety of ISO formats', () => {
check('P2W', { weeks: 2 });
});

test('Duration.fromISO can parse fractions of seconds', () => {

expect(Duration.fromISO('PT54M32.5S').toObject()).toEqual({ minutes: 54, seconds: 32, milliseconds: 500 });
expect(Duration.fromISO('PT54M32.53S').toObject()).toEqual({ minutes: 54, seconds: 32, milliseconds: 530 });
expect(Duration.fromISO('PT54M32.534S').toObject()).toEqual({ minutes: 54, seconds: 32, milliseconds: 534 });
expect(Duration.fromISO('PT54M32.5348S').toObject()).toEqual({ minutes: 54, seconds: 32, milliseconds: 534 });
expect(Duration.fromISO('PT54M32.034S').toObject()).toEqual({ minutes: 54, seconds: 32, milliseconds: 34 });
});

test('Duration.fromISO rejects junk', () => {
const rejects = s => {
expect(Duration.fromISO(s).isValid).toBe(false);
Expand Down

0 comments on commit 5a62569

Please sign in to comment.