Using javascript or jquery to auto populate the current time

I am trying to use javascript and / or jquery to auto-fill time in a time field of type; not a date. It fills in everything automatically. However, I am trying to have it automatically fill in the current time and not a specific time. (for example, "17:40:11")

How to get the current time from javascript or jquery and auto-fill it in the input time field?

Below, my code is pasted and the following error I get using Javascript.

Ive tried using jquery with new Date($.now());

, but I get a similar error, but my time is a bunch of numbers (e.g. 123435334)

Thanks for any help.

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

})

      

Mistake

jquery.js: 7373:

The specified value "7:13:40" does not match the required format. Format: "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.

+3


source to share


2 answers


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    
}

      

+3


source


Your problem is that getHours () returns 12 hour format. Several ways to fix it. You can check if the hour is less than 10 and then add a leading "0". But I would rather pass this link on to you:

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



where you can read a little more about formatting dates in javascript.

0


source







All Articles