Skip to content

Instantly share code, notes, and snippets.

@dserodio
Created July 1, 2022 18:36
Show Gist options
  • Save dserodio/a76a586c1887eb3891393a046763078f to your computer and use it in GitHub Desktop.
Save dserodio/a76a586c1887eb3891393a046763078f to your computer and use it in GitHub Desktop.
Google Apps Script for parsing duration strings
/* Based on: https://stackoverflow.com/a/44018490/31493 */
var duration = /(-?\d*\.?\d+(?:e[-+]?\d+)?)\s*([a-zμ]*)/ig
/**
* conversion ratios
*/
/**
* convert `str` to ms
*
* @param {String} str
* @return {Number}
*/
function parseDuration(str){
var result = 0
var error = null;
// ignore commas
str = str.replace(/(\d),(\d)/g, '$1$2')
if (/^\d+$/.test(str)) result = str*60;
else if (str.indexOf(':')>=0) {
var arr = str.split(':')
if (arr.length != 2) error = true;
else result = parseInt(arr[0])*60+ parseInt(arr[1])
}
else if (duration.test(str)) str.replace(duration, function(_, n, units){
units = getUnits(units)
|| getUnits[units.toLowerCase().replace(/s$/, '')]
|| undefined;
console.log(n)
if (typeof units === 'undefined') error = true;
else result += parseFloat(n, 10) * units;
})
else error = true;
return error ? null : result;
}
function getUnits(unit){
var to_ret;
switch(unit){
case "seconds":
case "second":
case "secs":
case "sec":
case "s": to_ret = 0; break;
case "minutes":
case "minute":
case "mins":
case "min":
case "m": to_ret = 1; break;
case "hours":
case "hour":
case "hr":
case "hrs":
case "h": to_ret = 60; break;
case "days":
case "day":
case "d": to_ret = 24 * 60; break;
case "weeks":
case "week":
case "w": to_ret = 7 * 24 * 60; break;
default: to_ret = undefined;
}
return to_ret;
}
function stripSeconds(str) {
return str.replaceAll(/\d+s/g, '')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment