/** Author Lidlanca **/
//dependency moment.js, jquery.js
/**
return an object understood by moment.duration
**/
function parseTime(humanTime, options) {
var opt = {
debug: false,
addOnRepeat: false, //if on, repeating time unit will be summedup
failOnRepeat: false //if on parse fail completly When repeated time unit detected, has not affact when addOnRepeat==true
}
var opt = $.extend(opt, options); // jquery dependency
p = /(\d+)(\D)/gi
var tt = humanTime;
var moment_obj = {};
while (m = p.exec(tt)) {
if (moment_obj.hasOwnProperty(m[2])) {
if (opt.addOnRepeat) {
moment_obj[m[2]] = parseInt(moment_obj[m[2]]) + parseInt(m[1]);
} else {
if (opt.failOnRepeat) return false;
console.warn("parseTime: Detected repeating time unit in input");
}
} else {
moment_obj[m[2]] = m[1];
}
if (opt.debug) console.log(m); //show match DEBUG
}
if (opt.debug) console.log(moment_obj);
return moment_obj;
}
//-----------------
//Testing and usage
//-----------------
function testParse(input_str, opt) {
outputDiv = $("#a");
r = parseTime(input_str, opt);
var outputTimeDays = (moment.duration(r).asDays().toFixed(2));
var outputTimeHours = (moment.duration(r).asHours().toFixed(2));
var outputTimeMinutes = (moment.duration(r).asMinutes().toFixed(2));
outputDiv.append(input_str + " => " + outputTimeDays + " Days", "<br>");
outputDiv.append(input_str + " => " + outputTimeHours + " Hours", "<br>");
outputDiv.append(input_str + " => " + outputTimeMinutes + " Minutes", "<br><br>");
}
testParse("1d 5m 1d", {
addOnRepeat: true
}); //only the last 2d count
testParse("1d 5m 1d", {
addOnRepeat: false
}); //only the last 2d count
testParse("1d 5m 1d", {
addOnRepeat: false,
failOnRepeat: true
}); //will fail
testParse("1d 5m 1d", {
addOnRepeat: true,
failOnRepeat: true
}); //will not fail failOnrepeat only count if addOnRepeat is on
<pre id="a"></pre>
External resources loaded into this fiddle: