Hello Friends 👋,

Welcome To Infinitbility! ❤️

To get the current datetime in typescript has the Date() object it will return every time the current date and time when we use it.

we have to just write new Date() and it returns the date object where we get a year, month, date, hours, minutes, and seconds.

let today: object = new Date();
console.log(today); // 2022-02-06T08:05:49.292Z

Now, we know we have the current date time but we can’t show the same to also users.

To format, we have multiple packages like Day.js, and Moment.js.

But if wanna follow a custom formater follow the below code.

function getCurrentTime() {
    let today: object = new Date();
    let hours: number = (today.getHours() < 10 ? '0' : '') + today.getHours();
    let minutes: number = (today.getMinutes() < 10 ? '0' : '') + today.getMinutes();
    let seconds: number = (today.getSeconds() < 10 ? '0' : '') + today.getSeconds();
    return hours + ':' + minutes + ':' + seconds;
}
console.log(getCurrentTime()); // '15:08:42'

Output

typescript, current, time, example
TypeScript, get current time example.

In above example, we are extracting and formating new Date() to time in typescript.

Thanks for reading…