How to get the current date and time with milliseconds accuracy in JavaScript

1 Answer

0 votes
function getCurrentDateTimeWithMillisecondsAccuracy() {
    const now = new Date();

    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    const milliseconds = now.getMilliseconds().toString().padStart(3, '0');

    const dateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;

    return dateTime;
}


const currentDateTime = getCurrentDateTimeWithMillisecondsAccuracy();

console.log(currentDateTime); 


   
/*
run:
   
2024-12-06 10:24:40.149
   
*/

 



answered Dec 6, 2024 by avibootz
...