156

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.

undefined
  • 1,019
  • 12
  • 24
Sender
  • 6,660
  • 12
  • 47
  • 66
  • 2
    If you pick a date on your fiddle and inspect the result frame, doing a `$('#datePicker').val();` gives `"2012-09-10"` and that's not the format you use for setting the date –  Sep 10 '12 at 06:33
  • It working in chrome on my end.. What do you exactly mean by `its not working`? – AdityaParab Sep 10 '12 at 06:34
  • try : `{ currentText: "Now" }`, see [manual](http://jqueryui.com/demos/datepicker/#option-currentText) – xkeshav Sep 10 '12 at 06:35
  • working on me... what is the problem? – Netorica Sep 10 '12 at 06:36
  • @RC, i will try `2012-09-10` this format but still not work. – Sender Sep 10 '12 at 06:37
  • `$('#datePicker').val("2012-09-01");` works for me –  Sep 10 '12 at 06:37
  • what is your computer's date time formate? – Jigar Pandya Sep 10 '12 at 06:38
  • 1
    @JigarPandya fr_FR (@user108, see also http://stackoverflow.com/a/3496622/180100) –  Sep 10 '12 at 06:39
  • my computer date formate `dd/MM/yyyy` – Sender Sep 10 '12 at 06:40
  • Please let me know the plugin you have used for the date picker. Probably trick can be done in the plugin... thanks – Dhanasekar Murugesan Sep 10 '12 at 07:12
  • This [link](http://updates.html5rocks.com/2012/08/Quick-FAQs-on-input-type-date-in-Google-Chrome) states that chrome has changes policy after version 20; so if you are using newer version the above would fail perhaps. In that case you need to alter the logic in javascript to match your exact needs base on version of chrome. you can detect version using http://stackoverflow.com/questions/5916900/detect-version-of-browser – Jigar Pandya Sep 10 '12 at 06:46
  • It works but your date has to be in this format `YYYY-MM-DD` – Dominic Mar 05 '14 at 14:50
  • you can use below date function var today = new Date().toISOString().split('T')[0]; $("#datePicker").val(today); – Gourav Makhija Oct 14 '18 at 12:16

14 Answers14

220

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);
Groot
  • 13,943
  • 6
  • 61
  • 72
Dhanasekar Murugesan
  • 3,141
  • 1
  • 18
  • 21
176

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

should work.

undefined
  • 1,019
  • 12
  • 24
int32_t
  • 5,774
  • 1
  • 22
  • 20
36
var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);

Above code will work.

Gourav Makhija
  • 710
  • 7
  • 16
  • 1
    be warned the val() part of the input is local time while toISOString() outputs UCT-Time. Can result to the wrong date in or at least if using an input of type Date + Time will set the wrong hour. – René W. Sep 23 '22 at 21:02
28

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

Oli Beatson
  • 811
  • 10
  • 22
  • 2
    Works in safari – James Alvarez Oct 11 '17 at 17:47
  • 11
    **Note:** this gives a date in the UTC time zone. In contrast the top answer uses local time. – Qwertie Aug 11 '18 at 02:49
  • 2
    @OlivUtilo—No, they do not for the period of the timezone offset for the host. – RobG Feb 02 '19 at 04:28
  • 1
    As Qwertie says, this potentially gives the wrong answer if you are using a date without a time. eg Sat Sep 01 2018 00:00:00 GMT+0100 gets converted to "2018-08-31" – havlock Aug 29 '19 at 17:51
  • [deleted previous comment for inaccuracy] so I'm thinking, time zone needs to be set on `date` then in this case (or forced to utc 0 before `toISOString`?) – Oli Beatson Oct 13 '20 at 12:45
  • https://stackoverflow.com/a/6777470/1140630 may be a good way to Date instance now in UTC – Oli Beatson Oct 13 '20 at 12:48
  • 1
    The UTC format of this answer is a huge problem and makes this one line answer... well not one-line anymore. You have to add or subtract hours depending on the GMT and light saving before converting toISOString – Radim Nyč May 28 '21 at 23:26
19

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);
Umair Khalid
  • 2,259
  • 1
  • 21
  • 28
  • 1
    yeah just like $('#datePicker').val(moment().format('YYYY-MM-DD')); – Umair Khalid Feb 06 '17 at 11:33
  • 2
    For people unfamiliar with Moment, if you want to format an arbitrary Javascript Date object with moment(): `var yourFormattedDate= moment(yourDate).format('YYYY-MM-DD');` `$('#datePicker').val(yourFormattedDate);` – veuncent Jan 11 '18 at 12:54
  • 1
    I would recommend against this. Downloading a library to do something relatively easy. But as of 2021 moment.js is a legacy project anyway – Radim Nyč May 28 '21 at 23:29
7

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

Dominic
  • 62,658
  • 20
  • 139
  • 163
5

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())
aashah7
  • 2,075
  • 1
  • 17
  • 24
5

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'}}" />
Ron
  • 5,900
  • 2
  • 20
  • 30
4

2021

A great way I found to do this is using locale for the formatting. You can use it in many different ways. This works for when you aren't using the jquery datepicker, but the html datepicker.

  $("#datepickerEnd").val(new Date().toLocaleDateString('en-CA'));//YYYY-MM-dd

Or split up for manipulation or adjustments or other uses.

let theDate = new Date();
  $("#datepickerEnd").val(theDate.toLocaleDateString('en-CA'));//YYYY-MM-dd

Manipulation example.

  theDate.setDate(theDate.getDate()-7);
  $("#datepickerStart").val(theDate.toLocaleDateString('en-CA'));//YYYY-MM-dd

The 'en-ca' is the needed format for my datepicker. If yours is different you can look for a string format that matches. Since it turns it to a string it does not contain extra information for messing up per region. So, in this way you can use it for purely formatting.

For more information

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Draco
  • 118
  • 2
  • 11
2

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Eda Jede
  • 81
  • 6
2

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);
Fendy
  • 21
  • 2
1

Try This,

$('#datePicker').val(moment().format('YYYY-MM-DD'));

Note : You need to add Moment.js as a dependency

abhi
  • 3,110
  • 1
  • 15
  • 17
Merrin K
  • 1,602
  • 1
  • 16
  • 27
0

A solution in one expression:

$('#datePicker').val(
    new Date()
    .toLocaleDateString("en-US", 
    {year:"numeric",month:"2-digit",day:"2-digit"})
   .replace(/(\d+).(\d+).(\d+)/,"$3-$2-$1")
)
webstermath
  • 555
  • 1
  • 5
  • 14
-6

Jquery version

var currentdate = new Date();

$('#DatePickerInputID').val($.datepicker.formatDate('dd-M-y', currentdate));
Seb33300
  • 7,464
  • 2
  • 40
  • 57