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?


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

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

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


Try

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

Or

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