How Do I Get the Current Time Only in Javascript

How can I get the current time in JavaScript and use it in a timepicker?

I tried var x = Date() and got:

Tue May 15 2012 05:45:40 GMT-0500

But I need only current time, for example, 05:45

How can I assign this to a variable?

3

21 Answers

var d = new Date("2011-04-20T09:30:51.01");
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51

or

var d = new Date(); // for now
d.getHours(); // => 9
d.getMinutes(); // =>  30
d.getSeconds(); // => 51
2

Short and simple:

new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM

4 hours later (use milisec: sec==1000):

new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48

2 days before:

new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015
4

Get and set the current time efficiently using javascript

I couldn't find a solution that did exactly what I needed. I wanted clean and tiny code so I came up with this:

(Set once in your master.js and invoke when required.)

PURE JAVASCRIPT

function timeNow(i) {
  var d = new Date(),
    h = (d.getHours()<10?'0':'') + d.getHours(),
    m = (d.getMinutes()<10?'0':'') + d.getMinutes();
  i.value = h + ':' + m;
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />

UPDATE

There is now sufficient browser support to simply use: toLocaleTimeString

For html5 type time the format must be hh:mm.

function timeNow(i) {
  i.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />

Try it on jsfiddle

5

Try

new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");

Or

new Date().toTimeString().split(" ")[0];
1

You can simply use this methods.

console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));
1
const date = Date().slice(16,21);
console.log(date);

Do you mean:

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

Try this:

var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
function getCurrentTime(){
    var date = new Date();
    var hh = date.getHours();
    var mm = date.getMinutes();

    hh = hh < 10 ? '0'+hh : hh; 
    mm = mm < 10 ? '0'+mm : mm;

    curr_time = hh+':'+mm;
    return curr_time;
}
1

This how you can do it.

const date = new Date();
const time = date.toTimeString().split(' ')[0].split(':');
console.log(time[0] + ':' + time[1])
2

See these Date methods ...

  • toLocaleTimeString -

  • toTimeString -

this -

var x = new Date(); 
var h = x.getHours(); 
var m = x.getMinutes(); 
var s = x.getSeconds(); 

so-

 x = date
h = hours
m = mins
s = seconds

A simple way to do this in ES6, in the format you requested (hh:mm), would be this way:

const goodTime = `${new Date().getHours()}:${new Date().getMinutes()}`;

console.log(goodTime);

(Obviously, the console logging is not part of the solution)

3

Try this

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

or

new Date().toTimeString().split(" ")[0];

It should work.

This is the shortest way.

var now = new Date().toLocaleTimeString();
console.log(now)

Here is also a way through string manipulation that was not mentioned.

var now = new Date()
console.log(now.toString().substr(16,8))
1
var today = new Date();  //gets current date and time
var hour = today.getHours();         
var minute = today.getMinutes();
var second = today.getSeconds();
1

Simple functions to get Date and Time separated and with compatible format with Time and Date HTML input

function formatDate(date) {
  var d         = new Date(date),
      month = '' + (d.getMonth() + 1),
      day   = '' + d.getDate(),
      year  = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}

function formatTime(date) {
        var hours   = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
        var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()

        return hours + ':' + minutes
}

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;
1

This worked for me but this depends on what you get when you hit Date():

Date().slice(16,-12)
2

Here is how I'm doing this: (Hope it helps someone) What I'm doing is validating the time that the user enters in the HTML time input is not in the past:

let inputTime = value; // from time input in html (06:29)

const splittedInputTime = inputTime.split(':');

let currentDate = new Date();
currentDate.setHours(splittedInputTime[0]);
currentDate.setMinutes(splittedInputTime[1]);

const finalInputTime = currentDate.toTimeString().split(" ")[0];

const currentTime = new Date().toTimeString().split(" ")[0];

// Returns a boolean (true/ false)
let validTime = finalInputTime >= currentTime;
var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        console.log(strTime);
        $scope.time = strTime;

        date.setDate(date.getDate()+1);
        month = '' + (date.getMonth() + 1),
        day = '' + date.getDate(1),
        year = date.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        var tomorrow = [year, month, day].join('-');
        $scope.tomorrow = tomorrow;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest