Set date in input type date

I will set today's date in the datepicker input type date in Chrome.

$(document).ready(function() {
    let now = new Date();
    let today = now.getDate()  + '/' + (now.getMonth() + 1) + '/' + now.getFullYear();
    console.log(today);
    $('#datePicker').val(today);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="datePicker" type="date">

However, it is not working.

Please try the code snippet in Chrome.


Solution 1:

Fiddle link : http://jsfiddle.net/7LXPq/93/

Two problems in this:

  1. Date control in HTML 5 accepts in the format of Year - month - day as we use in SQL
  2. If the month is 9, it needs to be set as 09 not 9 simply. So it applies for day field also.

Please follow the fiddle link for demo:

var now = new Date();

var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);

var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

$('#datePicker').val(today);

Solution 2:

document.getElementById("datePicker").valueAsDate = new Date()

should work.

Solution 3:

Update: I'm doing this with date.toISOString().substr(0, 10). Gives the same result as the accepted answer and has good support.