最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formatting milliseconds to always 3 digits for d.getMilliseconds() call - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked May 1, 2018 at 3:24 Alexander MillsAlexander Mills 101k166 gold badges537 silver badges918 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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>

发布评论

评论列表(0)

  1. 暂无评论