Skip to content Skip to sidebar Skip to footer

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); s

Solution 1:

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

setInterval(() => {
  const str = String(newDate().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.

Solution 2:

toFixed(3) gives you three digits after the decimal point, not before the decimal point, and getMilliseconds() returns an integer value with no significant digits after the decimal point -- so that's why you always get a number ending in .000.

So, as suggested by another poster, you can use padStart. If you didn't want to use that, you could do:

(1000 + new Date().getMilliseconds()).toString().substr(1);

Solution 3:

For just the milliseconds, in boring fundamentals:

let m = newDate().getMilliseconds();
if     (m<1){m = "000";}
elseif(m<10){m = "00" + m;}
elseif(m<100){m = "0" + m;}

Still using fundamentals; now with interactivity and the whole time, with milliseconds.

var myVar = setInterval(myTimer, 100);
functionmyTimer() {
  let d = newDate();
  let m = d.getMilliseconds();
  
  if(m<1){m = "000" + m;}
  elseif(m<10){m = "00" + m;}
  elseif(m<100){m = "0" + m;}
  
  var dateString = d.toLocaleTimeString();
  dateString = dateString.replace(" AM", "." + m + " AM");
  dateString = dateString.replace(" PM", "." + m + " PM");
  
  document.getElementById("demo").innerHTML = dateString;
}
<p>Start and stop this clock (always starts at current time with milliseconds):</p><pid="demo">Time at some time</p><buttonid="stop"onclick="clearInterval(myVar);
    document.getElementById('restart').style.display='block';
    document.getElementById('stop').style.display='none';"style="display:block;"
>Stop time</button><buttonid="restart"onclick="myVar = setInterval(myTimer, 100);
    document.getElementById('restart').style.display='none';
    document.getElementById('stop').style.display='block';"style="display:none;"
>Restart time</button>

Post a Comment for "Formatting Milliseconds To Always 3 Digits For D.getmilliseconds() Call"