How to Get Current Time in JavaScript ?
Last Updated :
12 Mar, 2024
This article will show you how to get the current time in JavaScript. Whether you are creating a digital clock, scheduling events, or simply logging timestamps, knowing how to retrieve the current time is essential.
Here, we will cover different methods to get the current time in JavaScript.
Using the Date Object
The Date object in JavaScript is used to work with dates and times. You can get the current date and time by creating a new instance of the Date object.
Example: This example shows the use of the above-mentioned approach.
Javascript
let currentTime = new Date();
console.log(currentTime);
Output2024-03-12T07:14:22.217Z
This will output the current date and time in the default format, which includes the full date along with the time.
You can extract specific components of the time, such as hours, minutes, and seconds, using the getHours(), getMinutes(), and getSeconds() methods of the Date object. This will output the current time in the format “Hours:Minutes:Seconds”.
Example: This example shows the use of the above-mentioned approach.
Javascript
let now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
console.log(`Current Time: ${hours}:${minutes}:${seconds}`);
OutputCurrent Time: 7:14:22
You might want to format the time in a specific way, such as ensuring that minutes and seconds are always displayed with two digits. You can achieve this by adding a leading zero to single-digit numbers.
Example: This example shows the use of the above-mentioned approach.
Javascript
function formatTime(number) {
return number < 10 ? '0' + number : number;
}
let now = new Date();
let hours = formatTime(now.getHours());
let minutes = formatTime(now.getMinutes());
let seconds = formatTime(now.getSeconds());
console.log(`Current Time: ${hours}:${minutes}:${seconds}`);
OutputCurrent Time: 07:14:21
In this example, the formatTime function adds a leading zero to numbers less than 10. This ensures that the time is always displayed in a consistent format, even when minutes or seconds are single digits.
Share your thoughts in the comments
Please Login to comment...