[javascript] set date in input type date

<input id="datePicker" type="date" />?

i will set today date in datepicker input type date in chrome.

$(document).ready( function() {
    var now = new Date();
    var today = now.getDate()  + '/' + (now.getMonth() + 1) + '/' + now.getFullYear();
    alert(today);
    $('#datePicker').val(today);
});?

but it's not working

Edit This jsFiddle - Please try in chrome.

This question is related to javascript html jquery date

The answer is


Your code would have worked if it had been in this format: YYYY-MM-DD, this is the computer standard for date formats http://en.wikipedia.org/wiki/ISO_8601


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.


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

should work.


var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);

Above code will work.


Jquery version

var currentdate = new Date();

$('#DatePickerInputID').val($.datepicker.formatDate('dd-M-y', currentdate));

    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.


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

You can only use date in input type="date" as in format YYYY-MM-DD

I have implemented helper as formatDate in NODE.js express-handlebars, don't need to be worry ... just use format as described in first line.

e.g:

< input type="date" id="date" name="date" class="form-control" value="{{formatDate invoice.date 'YYYY-MM-DD'}}" />

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


I usually create these two helper functions when using date inputs:

// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
  `${date.getFullYear()
  }-${('0' + (date.getMonth() + 1)).slice(-2)
  }-${('0' + date.getDate()).slice(-2)
  }`;

// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));

You can then set the date input value as:

$('#datePicker').val(dateToInput(new Date()));

And retrieve the selected value like so

const dateVal = inputToDate($('#datePicker').val())

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?