i will set today date in datepicker input type date in chrome.
$(
1 console.log(new Date())
2. document.getElementById("date").valueAsDate = new Date();
1st log showing correct in console =Wed Oct 07 2020 00:40:54 GMT+0530 (India Standard Time)
2nd 06-10-2020 which is incorrect and today date is 07 and here showing 06.
Fiddle link : http://jsfiddle.net/7LXPq/93/
Two problems in this:
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);
Update: I'm doing this with date.toISOString().substr(0, 10)
. Gives the same result as the accepted answer and has good support.
Datetimepicker always needs input format YYYY-MM-DD, it doesn't care about display format of your model, or about you local system datetime. But the output format of datetime picker is the your wanted (your local system). There is simple example in my post.
For me the shortest way to get locale date and in correct format for input type="date"
is this :
var d = new Date();
var today = d.getFullYear()+"-"+("0"+(d.getMonth()+1)).slice(-2)+"-"+("0"+d.getDate()).slice(-2);
Or this :
var d = new Date().toLocaleDateString().split('/');
var today = d[2]+"-"+("0"+d[0]).slice(-2)+"-"+("0"+d[1]).slice(-2);
Then just set the date input value :
$('#datePicker').val(today);
to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);