duration-fns
A collection of JavaScript functions for working with durations.
Installation
npm install duration-fns
Overview
import * as duration from 'duration-fns'
duration.parse('PT1M30S')
duration.toString({ years: 1, hours: 6 })
duration.toUnit({ minutes: 2 }, 'seconds')
duration.toMilliseconds({ seconds: 2 })
duration.toSeconds({ milliseconds: 2000 })
duration.toMinutes({ hours: 1, seconds: 60 })
duration.toHours({ minutes: 60 })
duration.toDays({ weeks: 1, hours: 24 })
duration.toWeeks({ days: 14 })
duration.toMonths({ years: 2, months: 1 })
duration.toYears({ months: 12 })
duration.normalize({ days: 28, hours: 24 })
duration.normalize({ days: 28, hours: 24 }, '2018-02-01')
duration.normalize({ days: 28, hours: 24 }, '2016-02-01')
duration.abs({ days: -1, seconds: 1 })
duration.negate({ days: -1, hours 2 })
duration.isNegative({ days: 1, hours: -25 })
duration.isZero({ days: 1, hours: -24 })
duration.subtract({ days: 2 }, { days: 1, hours: 12 })
duration.sum({ days: 1 }, { days: 2, hours: 12 })
duration.apply('2020-01-01T00:00:00.000Z', { years: 2 }).toISOString()
duration.between('2022-01-01', '2020-01-01')
duration.UNITS
Conventions
Function arguments
All functions that accept a duration object also accept numbers and strings:
duration.toSeconds({ minutes: 1 });
duration.toSeconds(60000);
duration.toSeconds('PT1M');
duration.sum({ seconds: 1 }, 'P1D', 200);
Normalization
Functions that transform or combine duration objects will not usually convert values between units:
duration.sum({ seconds: 1 }, { milliseconds: 1000 });
Pass the return values through normalize
for that functionality:
duration.normalize({ seconds: 1, milliseconds 1000 });
Some units cannot be normalized to others. For example, months can be normalized to years, but days cannot be normalized to months without a reference date:
duration.normalize({ days: 31 });
duration.normalize({ days: 31 }, '2020-02-01');
duration.normalize({ days: 31 }, '2020-12-01');
Misc
Test coverage report.