Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current time only in JavaScript

People also ask

How can I get the current Date and time?

The Clock. systemUTC(). instant() method returns the current date and time both.

What is now () in JavaScript?

now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.

How do you code time in JavaScript?

Javascript Clock Code (12 hours): function currentTime() { let date = new Date(); let hh = date. getHours(); let mm = date. getMinutes(); let ss = date. getSeconds(); let session = "AM"; if(hh == 0){ hh = 12; } if(hh > 12){ hh = hh - 12; session = "PM"; } hh = (hh < 10) ?


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];