DEV Community

Valeria
Valeria

Posted on

Day 18: Got a millisecond? ⏱️

Oh gosh, look how the time flies! Only 604800000 milliseconds left till Christmas! Wonder how I know? That's all thanks to a library called ms.

It does two things: converts strings to a number of milliseconds and the other way around. Here, let me demonstrate.

Install the library as usual, e.g. deno add npm:ms and create a file, e.g. main.ts:

import ms from 'ms'
console.log(`Milliseconds till Christmas: ${ms('7 days')}`)
Enter fullscreen mode Exit fullscreen mode

Now run with e.g. deno run -A ./main.ts:

deno run -A ./main.ts
# Milliseconds till Christmas: 604800000
Enter fullscreen mode Exit fullscreen mode

How about the other way around? Change main.ts to the following code:

import ms from 'ms'

console.log(`123 456 789 milliseconds is about ${ms(123456789, {long: true})}`)
Enter fullscreen mode Exit fullscreen mode

You'll hopefully find out that this amount of milliseconds is about a day: ms rounds up to the nearest sensible value, e.g:

import ms from 'ms'

console.log(ms(5000)) // 5s
console.log(ms(5499)) // 5s
console.log(ms(5500)) // 6s
console.log(ms(35000000)) // 10h
Enter fullscreen mode Exit fullscreen mode

Got any ideas how you'd use it? Share in the comments!

Liked the content and would love to have more of it all year long?

Buy Me A Coffee

Top comments (0)