Ms

ms a Tiny milisecond conversion utility, that does the below:

  • number -> (ms) -> string with a unit is returned.

  • string -> (ms) -> string

  • string+number with a valid unit -> (ms) -> number of equivalent ms

Installing: npm install ms

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var ms = require('ms');

ms('1d'); // 86400000

ms('1h'); // 3600000

ms('1m') // 60000

ms('1s') // 1000

ms('1000') // 1000

ms('1000',{long:true}) // 1000

ms(1000,{long:true}) // '1 second'

ms is one of those sweet tiny module that does exactly what is expected from it. The code is just 111 lines, logic is pretty simple, the method parses the given str and return milliseconds ;) well it also support short and long format for ms and has a Pluralization helper too.

Below as few selected chunks from the source code:

Helpers:

1
2
3
4
5
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;

Matcher:

1
/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i

Pluralization:

1
2
3
4
5
function plural(ms, n, name) {
  if (ms < n) return;
  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  return Math.ceil(ms / n) + ' ' + name + 's';
}

GIF FTW!

ms

Special thanks to Guillermo Rauch for this wonderful module :)

Suggest a module

Comments