Skip to content

Instantly share code, notes, and snippets.

@productioncoder
Created October 22, 2018 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save productioncoder/a8abe9a3f3b2a3a36e0e5cd674f5e355 to your computer and use it in GitHub Desktop.
Save productioncoder/a8abe9a3f3b2a3a36e0e5cd674f5e355 to your computer and use it in GitHub Desktop.
Parse ISO8601 time string
const objMap = ['years', 'months','days', 'hours', 'minutes', 'seconds'];
const numbers = '\\d+(?:[\\.,]\\d{0,3})?';
const datePattern = `(${numbers}Y)?(${numbers}M)?(${numbers}D)?`;
const timePattern = `T(${numbers}H)?(${numbers}M)?(${numbers}S)?`;
const pattern = new RegExp(`P(?:${datePattern}(?:${timePattern})?)`);
export function parseISO8601TimePattern(durationString) {
// https://github.com/tolu/ISO8601-duration/blob/master/src/index.js
return durationString.match(pattern).slice(1).reduce((prev, next, idx) => {
prev[objMap[idx]] = parseFloat(next) || 0;
return prev
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment