Created
September 28, 2024 18:02
-
-
Save mike-seger/f110dbe05d8c562e84dbf38a5576da6c to your computer and use it in GitHub Desktop.
Light-Weight Javascript Duration Parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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