Skip to content

Instantly share code, notes, and snippets.

@hhamilto
Created March 24, 2013 16:04
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 hhamilto/5232458 to your computer and use it in GitHub Desktop.
Save hhamilto/5232458 to your computer and use it in GitHub Desktop.
This javascript function takes a human typed amount of time (like "1 hour 30 mins", or "1.25 hours and 3 seconds") and converts it into a number of seconds for easy programmatic manipulation. Couldn't find it anywhere, so I made it.
function parseTimeAmount(stime){
var tokens = stime.split(/\s/);
var seconds = 0;
for(var i = 0; i < tokens.length; i++){
var quantity = parseFloat(tokens[i]);
if(!isNaN(quantity)){
i++;
if(/sec/.test(tokens[i])){
seconds+=quantity;
}else if(/min/.test(tokens[i])){
seconds+=quantity*60;
}else if(/hour/.test(tokens[i])){
seconds+=quantity*60*60;
}else if(/day/.test(tokens[i])){
seconds+=quantity*60*60*24;
}
}
}
return seconds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment