Using JavaScript or jQuery to auto populate the current time

3k views Asked by At

I am trying to use JavaScript and/or jQuery to auto populate the time in an type time field; not the date. It auto populates fine. However, i am trying to have it auto populate the current time rather than a specified time. (e.g."17:40:11")

How do I get the current time from JavaScript or jQuery and auto populate it in an input time field?

Below, pasted is my code and the following error I am getting using JavaScript.

I've tried using jQuery with new Date($.now()); but I get a similar error but my time is a bunch of numbers (e.g. 123435334)

HTML

<input type="time" value="" />

JavaScript

$(document).ready(function myTimer() {
      
    var now = new Date(Date.now());
    var f = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();           
    $("input[type=time]").val(f);
    
})

error

jquery.js:7373 :

The specified value '7:13:40' does not conform to the required format. The format is 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS' where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999.

2

There are 2 answers

0
3pic On BEST ANSWER

Add zeros if missing...Idea:

if(hours<10) hours = "0"+hours;

$(document).ready(function myTimer() {
    var now = new Date(Date.now());
    var f = leadZero(now.getHours()) + ":" + leadZero(now.getMinutes()) + ":" + leadZero(now.getSeconds());           
    $("input[type=time]").val(f);

})

function leadZero(_something) {    
    if(parseInt(_something)<10) return "0"+_something;
    return _something;//else    
}
0
alexandergs On

Your problem is that getHours() is returning 12 hours format. Several ways for fixing it. You can check if the hour is less than 10 an then add a leading '0'. But, I rather give you this link:

http://blog.stevenlevithan.com/archives/date-time-format

where you can learn a bit more about formatting dates in javascript.