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

1 Answer

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

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

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

    return dateTime;
}


const currentDateTime: string = getCurrentDateTimeWithMillisecondsAccuracy();

console.log(currentDateTime); 


   
/*
run:
   
"2024-12-06 12:33:37.268"
   
*/

 



answered Dec 6, 2024 by avibootz
...