by Sai gowtham

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course