How can I convert duration with JavaScript, for example:
PT16H30M
You could theoretically get an ISO8601 Duration that looks like the following:
P1Y4M3W2DT10H31M3.452S
I wrote the following regular expression to parse this into groups:
(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?T(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)?
It's not pretty, and someone better versed in regular expressions might be able to write a better one.
The groups boil down into the following:
I wrote the following function to convert it into a nice object:
var iso8601DurationRegex = /(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?T(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)?/;
window.parseISO8601Duration = function (iso8601Duration) {
var matches = iso8601Duration.match(iso8601DurationRegex);
return {
sign: matches[1] === undefined ? '+' : '-',
years: matches[2] === undefined ? 0 : matches[2],
months: matches[3] === undefined ? 0 : matches[3],
weeks: matches[4] === undefined ? 0 : matches[4],
days: matches[5] === undefined ? 0 : matches[5],
hours: matches[6] === undefined ? 0 : matches[6],
minutes: matches[7] === undefined ? 0 : matches[7],
seconds: matches[8] === undefined ? 0 : matches[8]
};
};
Used like this:
window.parseISO8601Duration('P1Y4M3W2DT10H31M3.452S');
Hope this helps someone out there.
If you are using momentjs, they have ISO8601 duration parsing functionality available. You'll need a plugin to format it, and it doesn't seem to handle durations that have weeks specified in the period as of the writing of this note.