How to get the current time in JavaScript
In this tutorial, we are going to learn about two different ways to get the current time using JavaScript.
Getting the current time
We can get the current time by calling a toLocaleTimeString()
method on JavaScript new Date()
constructor.
The
toLocaleTimeString()
returns the current time as a string format according to the specified locale conventions.
Here is an example:
const current = new Date();
// By default US English uses 12hr time with AM/PM
const time = current.toLocaleTimeString("en-US");
console.log(time);
Output:
"5:25:25 AM"
You can also get the time without seconds (hh:mm
format) like this:
const current = new Date();
const time = current.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
});
console.log(time); // "5:25 AM"
You can also get the 24hr time instead of 12hr time (AM/PM) by passing hour12: false
to the options object:
const current = new Date();
const time = current.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: false
});
console.log(time); // "5:25"
Similarly, if you want a 12hr time (AM/PM) just set hour12
property to true
.
For more time formats, you can refer to my previous tutorial on How to format a time in JavaScript.