Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting milliseconds to always 3 digits for d.getMilliseconds() call

So I have this:

new Date().getMilliseconds();

however, on occasion this just yields just 1 or 2 digits, instead of 3.

So I tried using:

new Date().getMilliseconds().toFixed(3);

so that it always is 3 digits, but this seems to always yield 000, and I don't know why. Anyone know how to do this right?

like image 526
Alexander Mills Avatar asked Jan 28 '26 00:01

Alexander Mills


1 Answers

You can use padStart to pad the string to the desired length:

setInterval(() => {
  const str = String(new Date().getMilliseconds()).padStart(3, '0');
  console.log(str);
}, 99);

This is a somewhat new feature though, so you'll need a polyfill if you want to support older browsers.

like image 163
CertainPerformance Avatar answered Jan 30 '26 13:01

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!