Envious
Envious

Reputation: 487

Using Javascript to input time in HTML5 time field

I'm trying to create a function in JS that will fill in the html5 <input type=time> with a format like this hh:mm:ss.

function timeChange(){
var d = new Date();
d.getHours();
d.getMinutes();
d.getSeconds();

var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();

document.getElementById("time_in").value = (....);
}

I'm not sure how to code the .value for this. I've tried using .value = (hours":"minutes":"seconds); but that just gives me a compile error.

Anyone got ideas? I just need it in hh:mm:ss.

HTML5 code:

 <button type="button" onClick="timeChange()">Time</button>

 <input id="time_in" type="time" name="time_in">

Upvotes: 5

Views: 18081

Answers (4)

int32_t
int32_t

Reputation: 6150

var d = new Date();
// Need to create UTC time of which fields are same as local time.
d.setUTCHours(d.getHours(), d.getMinutes(), d.getSeconds(), 0);
document.getElementById("time_in").valueAsDate = d;

Upvotes: 1

Ryan
Ryan

Reputation: 5682

document.getElementById('time_in').value = hours + ":" + minutes + ":" + seconds;

Otherwise you're not creating one concatenated string.

Upvotes: 0

Shmiddty
Shmiddty

Reputation: 13967

The simplest way would be to grab the time string from the Date object:

var time = (new Date()).toTimeString().split(' ')[0];

The split allows us to remove the timezone portion of the string.

Upvotes: 0

freejosh
freejosh

Reputation: 11383

hours":"minutes":"seconds isn't concatenating the string, you need +s: hours+":"+minutes+":"+seconds

Upvotes: 6

Related Questions