milli, fork of ms
Use this package to easily convert various time formats to milliseconds.
It should be compatible with all modern JS runtimes.
It is a fork of the original ms package, which is abandoned with the latest (canary) version release being almost 3 years old.
Examples
import { ms } from "milli"
ms("2 days")
ms("1d")
ms("10h")
ms("2.5 hrs")
ms("2h")
ms("1m")
ms("5s")
ms("1y")
ms("100")
ms("-3 days")
ms("-1h")
ms("-200")
Convert from Milliseconds
import { ms } from "milli"
ms(60000)
ms(2 * 60000)
ms(-3 * 60000)
ms(ms("10 hours"))
Time Format Written-Out
import { ms } from "milli"
ms(60000, { long: true })
ms(2 * 60000, { long: true })
ms(-3 * 60000, { long: true })
ms(ms("10 hours"), { long: true })
Features
- If a number is supplied to
ms, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns
100 for "100")
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
TypeScript
If you want to pass a string variable into ms, you will need a type coercion to string:
import { ms } from "milli"
ms("1h" as never)
This is because of the literal types used for DevX, so you get proper completion in your IDE.
You can also use parse instead, which is a less strict version of passing a string into ms.
Advanced Usage
import { parse, format } from "ms"
parse("1h")
format(2000)
If you want strict type checking for the input value, you can use parseStrict.
import { parseStrict } from "ms"
parseStrict("1h")
function example(s: string) {
return parseStrict(str)
}