我正在开展一个项目,用户需要提供特定任务的时间估算。我想知道是否已经有一个脚本(如date.js)可以接受用户输入并将其解析为秒数。
Examples:
"2 days" = 172800
"2 hours" = 7200
"1d 5h" = 104400
"15 minutes" = 900
date.js非常适合查找将来的具体日期,但我需要总秒数,而不是特定的结束日期。
如果它不存在,我会自己编码,只是想节省一些时间。
答案 0 :(得分:3)
这是我头顶的一个图书馆(抱歉,我无法抗拒)
var stringToSeconds = (function() {
//Closure to define things that
//do not change per function call
var reg = /(\d+)\s*(\w+)/g;
var units = {};
//Lets be verbose
units.seconds = 1;
units.minutes = units.seconds * 60;
units.hours = units.minutes * 60;
units.days = units.hours * 24;
units.weeks = units.days * 7;
units.months = units.weeks * 4;
units.years = units.months * 12;
//Match unit shorthand
var getUnit = function(unit) {
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;
};
return function(str) {
var match, totalSeconds = 0;
while (match = reg.exec(str)) {
var num = match[1], unit = match[2];
totalSeconds += getUnit(unit) * num;
}
return totalSeconds;
}
}());
答案 1 :(得分:0)
对单位价值进行了更改,数月的计算弄乱了几年。
units.seconds = 1;
units.minutes = 60;
units.hours = 3600;
units.days = 86400;
units.weeks = 604800;
units.months = 262974383;
units.years = 31556926;
答案 2 :(得分:0)
这是我最终的工作版本,基于MooGoo优秀的脚本。在进行了一些bug /浏览器测试之后,我会对此进行更新。
如果您有任何改进,请告诉我们。)
演示: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 '';
}
};