Here is my final working version, based off of MooGoo's excellent script. Ill update this after some more bug/browser testing.
Please let me know if you have any improvements :)
- added support for decimals. 1.5 hours = 1 hour 30 minutes
- added get_string function. Pass in number of seconds and get a formatted string.
- made it so the number defaults to hours. 5 = 5 hours
Demo: http://jsbin.com/ihuco3/2/edit
var string2seconds = {
reg: /([\d]+[\.]?[\d{1,2}]?)\s*(\w+)/g,
units: function()
{
var units = {};
units.seconds = 1;
units.minutes = 60;
units.hours = 3600;
units.days = 86400;
units.weeks = 604800;
units.months = 262974383;
units.years = 31556926;
return units;
},
get_unit: function(unit)
{
var units = this.units();
unit = unit.toLowerCase();
for (var name in units)
{
if( !units.hasOwnProperty(name) ) continue;
if( unit == name.substr(0, unit.length) ) return units[name];
}
return 0;
},
get_string: function( seconds )
{
var years = Math.floor(seconds/31556926);
var days = Math.floor((seconds % 31556926)/86400);
var hours = Math.floor(((seconds % 31556926) % 86400) / 3600);
var minutes = Math.floor((((seconds % 31556926) % 86400) % 3600 ) / 60);
var string = '';
if( years != 0 ) string = string + years + ' year'+this.s(years)+' ';
if( days != 0 ) string = string + days + ' day'+this.s(days)+ ' ';
if( hours != 0 ) string = string + hours + ' hour'+this.s(hours)+ ' ';
if( minutes != 0 ) string = string + minutes + ' minute'+this.s(minutes)+ ' ';
if( string == '' ) return false;
return string;
},
get_seconds: function( str )
{
var match, totalSeconds = 0, num, unit;
if( (str - 0) == str && str.length > 0 )
{
str = str + 'hours';
}
while (match = this.reg.exec(str))
{
num = match[1];
unit = match[2];
totalSeconds += this.get_unit(unit) * num;
}
return totalSeconds;
},
s: function( count )
{
if( count != 1 ) return 's';
return '';
}
};