Formatting the Time

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}`);

Output
Current 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.


How to Get Current Time in JavaScript ?

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.

Table of Content

  • Using the Date Object
  • Extracting Time Components
  • Formatting the Time

Similar Reads

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....

Extracting Time Components

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”....

Formatting the Time

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....