1

Can you please let me know how to make sure that the milliseconds are always a 3 digit number. My code is currently giving the output of a three digit number only when the value of milisecs is 2 digit like "099" and if 1 digit I get this "0009" can you please solve this.

Js here

function time(){
var findDate=new Date();
var year=findDate.getFullYear() 
var findMonth=findDate.getMonth()
Var month=findMonth+1,day=findDate.getDate();
var hour=findDate.getHours()
var mins=findDate.getMinutes()
var second=findDa    te.getSeconds()
var milisec=findDate.getMilliseconds(),b="/",c=":";
if(day<10){day="0"+day} 
if(month<10){month="0"+month}
if(hour<10){hour="0"+hour}
if(mins<10){mins="0"+mins}
if(second<10){second="0"+second}
if(milisec<100){milisec="0"+milisec}
if(milisec<10){milisec="00"+milisec}
var date="Date="+day+b+month+b+year+" Time="+hour+c+mins+c+second+"."+milisec;
document.getElementById('time').innerHTML=date}

Html

<button class="time" type="button" onclick="time()">
What is the Date and Time?</button>
<p id="time" class="p" ></p>

.

User not found
  • 479
  • 3
  • 15

1 Answers1

1

To make sure you always get last 3 digits of a string, you can use slice function.

const milliSec = findDate.getMilliseconds();
const formattedMilliSec = `00${milliSec}`.slice(-3);
console.log(formattedMilliSec)
ravi
  • 1,130
  • 16
  • 29