In this article, I am going to show you how to get and display the current time in any format in JavaScript.
Step #1: Getting the date at the current time
const now = new Date();
Step #2: Displaying the current time
Let’s try some examples.
Example #1: The human-readable time portion
// 16:53:02 GMT+0700 (Indochina Time)
const text = now.toTimeString();
Example #2: The “HH:mm:ss” format (the local timezone)
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const padZero = value => value.toString().padStart(2, '0');
// 16:53:02
const text = [hours, minutes, seconds].map(padZero).join(':');
Example #3: The “HH:mm:ss” format (UTC+00:00)
const hours = now.getUTCHours();
const minutes = now.getUTCMinutes();
const seconds = now.getUTCSeconds();
const padZero = value => value.toString().padStart(2, '0');
// 09:53:02
const text = [hours, minutes, seconds].map(padZero).join(':');
Note: you only need to replace the get*()
methods with the getUTC*()
ones to get the corresponding UTC values.
Bonus tip: Date.prototype.toISOString()
always returns a string with zero UTC offset (the letter Z
at the end), so you can extract the time portion from the string result.
// 09:53:02
const text = now.toISOString().substring(11, 19);