是否有类似date.js的javascript解析器用于时间估计?
我正在做一个项目,用户需要提供特定任务的时间估计。我想知道是否已经有一个脚本(比如date.js)可以接受用户输入并将其解析到秒数是否有类似date.js的javascript解析器用于时间估计?,javascript,Javascript,我正在做一个项目,用户需要提供特定任务的时间估计。我想知道是否已经有一个脚本(比如date.js)可以接受用户输入并将其解析到秒数 Examples: "2 days" = 172800 "2 hours" = 7200 "1d 5h" = 104400 "15 minutes" = 900 js非常适合在将来查找特定日期,但我需要的是总秒数,而不是特定的结束日期 如果它还不存在,我会自己编写代码,只是想在它存在的时候节省一些时间。这是我脑海中的一个库(对不起,我无法抗拒) 试试看:对单位值
Examples:
"2 days" = 172800
"2 hours" = 7200
"1d 5h" = 104400
"15 minutes" = 900
js非常适合在将来查找特定日期,但我需要的是总秒数,而不是特定的结束日期
如果它还不存在,我会自己编写代码,只是想在它存在的时候节省一些时间。这是我脑海中的一个库(对不起,我无法抗拒)
试试看:对单位值进行了更改,几个月的计算结果把年份搞乱了
units.seconds = 1;
units.minutes = 60;
units.hours = 3600;
units.days = 86400;
units.weeks = 604800;
units.months = 262974383;
units.years = 31556926;
这是我的最终工作版本,基于MooGoo的优秀脚本。我会在更多的bug/browser测试之后更新这个 如果您有任何改进,请告诉我:)
- 增加了对小数的支持。1.5小时=1小时30分钟
- 添加了get_字符串函数。传入秒数并获取格式化字符串
- 使数字默认为小时。5=5小时
非常好:)工作起来很有魅力。从秒/分钟/小时/天/周的数量转换成月/年的数量是相当困难的,因为每月或每年的天数是不规则的,每个月和每年都会变化。是的,我正在考虑在我将脚本投入生产时,将其数月和数年去掉。在我的情况下不需要。@Justice是的,我意识到了这一点,但出于示例考虑,我还是想把它放进去。不过再想想,我可能更喜欢使用
newdate
构造函数来构建未来的时间戳,然后从中减去当前的时间戳。
units.seconds = 1;
units.minutes = 60;
units.hours = 3600;
units.days = 86400;
units.weeks = 604800;
units.months = 262974383;
units.years = 31556926;
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 '';
}
};