How to get the current time in JavaScript
In this post we will give you information about How to get the current time in JavaScript. Hear we will give you detail about How to get the current time in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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/PMconst 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.
Hope this code and post will helped you for implement How to get the current time in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs