get time in javascript

To get the current time in Javascript, you can use the Date() object and its methods such as getHours() and getMinutes().

index.tsx
// create a new date object
const now = new Date();
// get the current hour and minutes
const hours = now.getHours();
const minutes = now.getMinutes();
// print the time in HH:MM format
console.log(`Current time is ${hours}:${minutes}`);
238 chars
8 lines

If you need to format the time output in a different way, you can use the toLocaleTimeString() method which allows you to specify the locale and options:

index.tsx
const now = new Date();
const timeStr = new Intl.DateTimeFormat('en-US', { timeStyle: 'medium' }).format(now);
console.log(`Current time is ${timeStr}`);
154 chars
4 lines

This will give you the time in a format like 9:47:15 AM.

gistlibby LogSnag