Javascript Data Type How to - Convert '1 day' into 86400000








Question

We would like to know how to convert '1 day' into 86400000.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  w  w w .  j a v a 2 s.c  om-->
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);
}
document.writeln([strToMs('5 days'), strToMs('2.8 years'), strToMs('minutes: 20')])

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: