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