How to set datetime on datetime-local via jQuery

This would do the trick

$("#publishDate").val("2013-03-18T13:00");

You need to use 2 digits for the month to make your sample work.


If you want to set the current date, then you can try this:

__Method 1:__

$(document).ready(function(){
    $('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});

__Method 2:__

function zeroPadded(val) {
  if (val >= 10)
    return val;
  else
    return '0' + val;
}

$(document).ready(function(){
  d = new Date();
  $('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});

Note: You can replace $('input[type=datetime-local]') with Id or Name or Class of the datetime-local field.

EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.


What about?

var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));