Skip to content

Instantly share code, notes, and snippets.

@mike-seger
Created September 28, 2024 18:02
Show Gist options
  • Select an option

  • Save mike-seger/f110dbe05d8c562e84dbf38a5576da6c to your computer and use it in GitHub Desktop.

Select an option

Save mike-seger/f110dbe05d8c562e84dbf38a5576da6c to your computer and use it in GitHub Desktop.
Light-Weight Javascript Duration Parser
parseIso8601Duration(iso8601Duration) {
const iso8601DurationRegex = /(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?T{0,1}(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)?/;
const matches = iso8601Duration.match(iso8601DurationRegex);
return {
sign: matches[1] === undefined ? '+' : '-',
years: matches[2] === undefined ? 0 : Number(matches[2]),
months: matches[3] === undefined ? 0 : Number(matches[3]),
weeks: matches[4] === undefined ? 0 : Number(matches[4]),
days: matches[5] === undefined ? 0 : Number(matches[5]),
hours: matches[6] === undefined ? 0 : Number(matches[6]),
minutes: matches[7] === undefined ? 0 : Number(matches[7]),
seconds: matches[8] === undefined ? 0 : Number(matches[8])
}
}
iso8601Duration2Seconds(iso8601Duration) {
const d = parseIso8601Duration(iso8601Duration)
const f = d.sign === '-'? -1:1
const ds = 24*60*60
return f * (d.years*365*ds + d.months*30*ds + d.weeks*7*ds +
d.days*ds + d.hours*60*60 + d.minutes*60 + d.seconds )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment