3

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
albert rios
  • 55
  • 1
  • 5
  • I believe you need leading zeros on all of the hour, minute, and second components of the time. – rink.attendant.6 Jun 09 '15 at 14:43
  • This question was answered before. Please see [this article][1] [1]: http://stackoverflow.com/questions/8398897/how-to-get-current-date-in-jquery – Yuri Jun 09 '15 at 14:43
  • Look at the error: "and SSS is 000-999." but if you run new Date(Date.now()).getHours() + ":" + new Date(Date.now()).getMinutes() + ":" + new Date(Date.now()).getSeconds(); in the console you'll notice that seconds are in a different format – frenchie Jun 09 '15 at 14:43
  • do you want same affect as this one http://jsbin.com/zadasunaru/1/ – bmscomp Jun 09 '15 at 14:49
  • @Yuri , this is different than the link you posted. This has to do with a time input field... not a date.. these are two different questions. Thanks anyways for the help – albert rios Jun 09 '15 at 16:15

2 Answers2

3

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    
}
code-jaff
  • 9,230
  • 4
  • 35
  • 56
3pic
  • 1,188
  • 8
  • 26
0

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.

alexandergs
  • 182
  • 2
  • 12