How to show current time in JavaScript in the format HH:MM:SS?

JavascriptDatetime

Javascript Problem Overview


How do I show the current time in the format HH:MM:SS?

Javascript Solutions


Solution 1 - Javascript

You can use native function Date.toLocaleTimeString():

var d = new Date();
var n = d.toLocaleTimeString();

This will display e.g.:

"11:33:01"

MDN: Date toLocaleTimeString

var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);

Solution 2 - Javascript

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
startTime();

<div id="time"></div>

DEMO using javaScript only

Update

Updated Demo

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    startTime();
})();

Solution 3 - Javascript

You can do this in Javascript.

var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());

At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.

Check this in JSFiddle

Updates:
For prefixed 0's try

var time = new Date();
console.log(
	("0" + time.getHours()).slice(-2)   + ":" + 
	("0" + time.getMinutes()).slice(-2) + ":" + 
	("0" + time.getSeconds()).slice(-2));

Solution 4 - Javascript

You can use moment.js to do this.

var now = new moment();
console.log(now.format("HH:mm:ss"));

Outputs:

16:30:03

Solution 5 - Javascript

new Date().toTimeString().slice(0,8)

Note that toLocaleTimeString() might return something like 9:00:00 AM.

Solution 6 - Javascript

Use this way:

var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });

Result: 18:56:31

Solution 7 - Javascript

function realtime() {
  
  let time = moment().format('h:mm:ss a');
  document.getElementById('time').innerHTML = time;
  
  setInterval(() => {
    time = moment().format('h:mm:ss a');
    document.getElementById('time').innerHTML = time;
  }, 1000)
}

realtime();

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<div id="time"></div>

A very simple way using moment.js and setInterval.

setInterval(() => {
  moment().format('h:mm:ss a');
}, 1000)

Sample output

Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.

> 3:25:50 pm

This is how I use this method on one of my side projects.

setInterval(() => {
  this.time = this.shared.time;
}, 1000)

Maybe you're wondering if using setInterval() would cause some performance issues.

https://stackoverflow.com/questions/6650134/is-setinterval-cpu-intensive

> I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday

> No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth

> But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy

Solution 8 - Javascript

This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.

var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55

Solution 9 - Javascript

new Date().toLocaleTimeString('it-IT')

The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01

Solution 10 - Javascript

Compact clock function:

setInterval(function() {
    let d = new Date()
    console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);

Solution 11 - Javascript

This is an example of how to set time in a div(only_time) using javascript.

function date_time() {
    var date = new Date();
    var am_pm = "AM";
    var hour = date.getHours();
    if(hour>=12){
        am_pm = "PM";
    }
    if (hour == 0) {
        hour = 12;
    }
    if(hour>12){
        hour = hour - 12;
    }
    if(hour<10){
        hour = "0"+hour;
    }

    var minute = date.getMinutes();
    if (minute<10){
        minute = "0"+minute;
    }
    var sec = date.getSeconds();
    if(sec<10){
        sec = "0"+sec;
    }

    document.getElementById("time").innerHTML =  hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>

Solution 12 - Javascript

new Date().toLocaleTimeString()

Solution 13 - Javascript

function realtime() {
  
  let time = moment().format('hh:mm:ss.SS a').replace("m", "");
  document.getElementById('time').innerHTML = time;
  
  setInterval(() => {
    time = moment().format('hh:mm:ss.SS A');
    document.getElementById('time').innerHTML = time;
  }, 0)
}

realtime();

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<div id="time"></div>

Solution 14 - Javascript

Use

> Date.toLocaleTimeString()

// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');

console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM

console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30

console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠

Source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2648752View Question on Stackoverflow
Solution 1 - JavascriptpstrykView Answer on Stackoverflow
Solution 2 - JavascriptTushar Gupta - curioustusharView Answer on Stackoverflow
Solution 3 - JavascriptPraveenView Answer on Stackoverflow
Solution 4 - JavascriptbrandonscriptView Answer on Stackoverflow
Solution 5 - JavascriptThorstenView Answer on Stackoverflow
Solution 6 - JavascriptThomasView Answer on Stackoverflow
Solution 7 - Javascriptflyingpluto7View Answer on Stackoverflow
Solution 8 - JavascriptvanjavkView Answer on Stackoverflow
Solution 9 - JavascriptiamnotsamView Answer on Stackoverflow
Solution 10 - JavascriptByCodeXpView Answer on Stackoverflow
Solution 11 - JavascriptA.S.AbirView Answer on Stackoverflow
Solution 12 - JavascriptDilushanView Answer on Stackoverflow
Solution 13 - Javascriptvenetzia gajardoView Answer on Stackoverflow
Solution 14 - JavascriptMansour AshrafView Answer on Stackoverflow