is there a library that convert '1 day' into 86400000
I'm looking for a function that can convert 1 day
to 86400000
or 20 min
to 1200000
. I'm going from a readable string to a number of ms
Something like:
var key = { s: 100开发者_运维技巧0, m:1000*60, h:1000*60*60, d: 1000*60*60*24, ... },
m = str.match((\d+) (\w)),
result = m[1] * (key[m[2]] || 1);
The code you have should work pretty well. I took the basic idea and threw together a more flexible function that can combine units. It's extremely relaxed about what it accepts, but you could make it more strict if you wanted to.
(function() {
var units = {
ms: 1/1000,
m: 60,
min: 60, mins: 60,
minute: 60, minutes: 60,
h: 60*60,
hr: 60*60, hrs: 60*60,
hour: 60*60, hours: 60*60,
d: 60*60*24,
day: 60*60*24, days: 60*60*24,
};
Date.parseInterval = function(interval) {
var seconds = 0;
interval.replace(/(\d+(?:\.\d*)?)\s*([a-z]+)?/ig, function($0, number, unit) {
if (unit) {
number *= units[unit.toLowerCase()] || 1;
}
seconds += +number;
});
return seconds * 1000;
};
})();
console.log(Date.parseInterval('1 day') === 86400000);
console.log(Date.parseInterval('20 min') === 1200000);
console.log(Date.parseInterval('1 day, 3 hours, and 22.5 seconds') === 97222500);
strToMs = function(str) {
var multiplier = {
ms: 1, mil: 1, s:1000, sec: 1000, min: 1000*60,
hr: 1000*60*60, hrs: 1000*60*60, hou: 1000*60*60,
d: 1000*60*60*24, day: 1000*60*60*24, mon: 1000*60*60*24*30,
y: 1000*60*60*24*386.25, yea: 1000*60*60*24*386.25
},
num = str.match(/\d+/), units = str.match(/[a-z]{1,3}/i)
return num * (multiplier[units] || 1);
}
DEMO
The built-in Date object can handle a lot of stuff. Otherwise, something like http://www.datejs.com/ may be helpful
I've had success in the past using the datejs library for dates.
It seems to support parsing strings like now + 20 min
, so at worst you could subtract now
(or any fixed Date doesn't seem to support this), and then call getMilliseconds()
on that.
精彩评论