3

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?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

3 Answers3

6

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • yeah I can't decide if it should be padStart or padEnd... lol ... but I think you're right, it's probably supposed to be padStart – Alexander Mills May 01 '18 at 03:29
0

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);
kshetline
  • 12,547
  • 4
  • 37
  • 73
0

For just the milliseconds, in boring fundamentals:

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

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

var myVar = setInterval(myTimer, 100);
function myTimer() {
  let d = new Date();
  let m = d.getMilliseconds();
  
  if(m<1){m = "000" + m;}
  else if(m<10){m = "00" + m;}
  else if(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>

<p id="demo">Time at some time</p>

<button 
 id="stop" 
    onclick="clearInterval(myVar);
    document.getElementById('restart').style.display='block';
    document.getElementById('stop').style.display='none';" 
    style="display:block;"
>Stop time</button>

<button 
 id="restart" 
    onclick="myVar = setInterval(myTimer, 100);
    document.getElementById('restart').style.display='none';
    document.getElementById('stop').style.display='block';" 
    style="display:none;"
>Restart time</button>
Ed_Johnsen
  • 136
  • 8