Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Last active August 29, 2015 14:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanbrook/fe1271f733e5f85a60f4 to your computer and use it in GitHub Desktop.
Save johanbrook/fe1271f733e5f85a60f4 to your computer and use it in GitHub Desktop.
Parse a timestamp or duration like `3h2m1s` to total seconds.
/*
* Parses a human readable duration on the form
* and return the total duration in seconds.
*
* @param {string} - Timestamp on the form XhYmZs. Unit
* parts are optional: 3h2s, 3m1s, 4h2m
* are all valid.
*/
function parseTimestamp(timestamp) {
/**
* Wrapper around `parseInt`, but returns false
* if result is NaN.
*/
function parse(value) {
var intVal = parseInt(value)
return _.isNaN(intVal) ? false : intVal
}
return _.chain(timestamp.match(/(\d+h)?(\d+m)?(\d+s)?/i))
.last(3) // regex match result is in last three elements in array
.reverse() // reverse indexes (see below)
.reduce(function(seconds, value, index) {
/*
`value` is a string: '2h', etc. `index` will
signify the time unit (hour=2, min=1, seconds=0).
Use that to convert from hours/minutes to seconds:
*/
var intVal = parse(value)
// If the value is a parsable number, convert to
// seconds. Otherwise do nothing with end result `seconds`.
seconds += intVal ? intVal*(Math.pow(60, index)) : 0
return seconds
}, 0)
.value()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment