245

I have a very simple jQuery Datepicker calendar:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
});

and of course in the HTML...

<input type="text" size="10" value="" id="date_pretty"/>

Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Marcus
  • 5,772
  • 8
  • 35
  • 60
  • 7
    The most popular answer is better that accepted answer. it's better to change the accepted answer. – ahmadali shafiee Nov 09 '12 at 20:48
  • my related question http://stackoverflow.com/questions/25602649/jqueryui-datepicker-differences-between-defaultdate-option-vs-setdate-method – Adriano Sep 01 '14 at 10:01
  • 1
    @ahmadalishafiee (and everyone else). The currently accepted solution was accepted on 2015-05-07. – Teepeemm Mar 01 '18 at 17:10

19 Answers19

579

Update: There are reports this no longer works in Chrome.

This is concise and does the job (obsolete):

$(".date-pick").datepicker('setDate', new Date());

This is less concise, utilizing chaining allows it to work in chrome (2019-06-04):

$(".date-pick").datepicker().datepicker('setDate', new Date());
nulltron
  • 637
  • 1
  • 9
  • 25
CiscoIPPhone
  • 9,457
  • 3
  • 38
  • 42
  • 2
    This is the one that actually worked for me and not the accepted solution. Thank you – Mehdiway Sep 12 '13 at 09:46
  • I would like to suggest if the stackoverflow could just put the top voted answer on top, rather than as it's. E.g like what Youtube did is good. – William Nov 06 '13 at 07:45
  • +1, using the Date object is much cleaner & bug-proof. Note that you can use things such as `var myDate = new Date(); myDate.setFullYear(1985); myDate.setMonth(0); /* month is zero-based */ myDate.setDate(28);` see more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Adriano Sep 01 '14 at 10:00
  • 7
    This will not work, first you should call $(".date-pick").datepicker(); and then $(".date-pick").datepicker('setDate', new Date()); – Misha Akopov Jun 15 '15 at 04:53
  • 9
    Not longer works in Chrome after recent browser update – Max Flex Oct 21 '15 at 15:55
  • 2
    @QuinnDaley Thanks - I'm adding a warning to my answer. – CiscoIPPhone Nov 13 '15 at 18:20
  • 3
    Works. I'm setting `$(".date-pick").datepicker().datepicker('setDate', new Date()); ` tho – seebiscuit Jun 22 '17 at 14:39
227

You must FIRST call datepicker() > then use 'setDate' to get the current date.

$(".date-pick").datepicker();
$(".date-pick").datepicker("setDate", new Date());

OR chain your setDate method call after your datepicker initialization, as noted in a comment on this answer

$('.date-pick').datepicker({ /* optional option parameters... */ })
               .datepicker("setDate", new Date());

It will NOT work with just

$(".date-pick").datepicker("setDate", new Date());

NOTE : Acceptable setDate parameters are described here

Brett Weber
  • 1,839
  • 18
  • 22
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113
  • 3
    Using jQueryUI 1.8 I found this solution to be the only (sane) way to accomplish this. – brianz Dec 06 '12 at 23:20
  • 13
    $(".selector").datepicker().datepicker("setDate", new Date()); will work and doesn't make jQuery search the DOM twice. – abc123 Aug 01 '13 at 20:36
  • 1
    Great, accepted answer says only $(".date-pick").datepicker("setDate", new Date()); and it doesn't work without first call $(".date-pick").datepicker(); your answer is much better – Misha Akopov Jun 15 '15 at 04:52
72
var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);

seemed to work, but there might be a better way out there..

sth
  • 222,467
  • 53
  • 283
  • 367
lucas
  • 6,951
  • 4
  • 33
  • 34
  • This works pretty well except for two things: 1) I was kind of hoping to use jQuery method to get the current date, but maybe it doesn't matter. 2) this solution produces a value exactly one month previous to today's date! – Marcus Oct 24 '08 at 14:15
  • 2
    OH - you're right! check it out - http://www.w3schools.com/jsref/jsref_obj_date.asp - month is 0-11 - you'll have to add 1.. curiously, getDate is 1-31, but getMonth is 0-11.. – lucas Oct 24 '08 at 14:20
  • 3
    There is an easier way .. see my post below. – Ravi Ram Jan 20 '12 at 17:17
  • This solution let's to show text directly and set date simultaneously while CiscoIPPhone's solution needs another step to show the value without opening the picker. – Afshar Mohebi Feb 02 '12 at 20:26
  • 4
    For `setDate` you can also use the usual relative notation of datepicker, for example to get the following day just type `.datepicker('setDate', '+1d')`. – mutantacule Jun 05 '12 at 14:57
59

The setDate() method sets the date and updates the associated control. Here is how:

$("#datepicker1").datepicker({
    dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");

Demo

As mentioned in documentation, setDate() happily accepts the JavaScript Date object, number or a string:

The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

In case you are wondering, setting defaultDate property in the constructor does not update the associated control.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    Why is it in your demo it works. When I copy this code into my site the dialog keeps popping up when the pg loads. – chobo2 Sep 09 '12 at 00:38
  • 1
    This worked for me - the accepted answer and other options above didn't. – lydiat Dec 11 '15 at 19:29
  • This is a much, much better solution than any of the above. – adamj Feb 07 '17 at 06:04
  • Best answer for this question at the present time although I needed the date format to be "mm-dd-yy" to match the date picker. – John81 Apr 06 '17 at 16:31
26

Set to today:

$('#date_pretty').datepicker('setDate', '+0');

Set to yesterday:

$('#date_pretty').datepicker('setDate', '-1');

And so on with any number of days before or after today's date.

See jQuery UI › Methods › setDate.

KirilleXXI
  • 261
  • 3
  • 2
  • 1
    Great, as others have mentioned, you must have called datepicker() once already so, `$(".date-pick").datepicker("setDate", '+0');` – jwbensley Mar 22 '13 at 17:37
  • This also worked as I wished, since my dateFormat needs to match MySQL's date format (yy-mm-dd). This setDate adds zero padding to the month and day. – jjohn Oct 08 '14 at 17:34
9

The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
Marcus
  • 5,772
  • 8
  • 35
  • 60
7

This one worked for me.

$('#inputName')
  .datepicker()
  .datepicker('setDate', new Date());
Celestz
  • 301
  • 3
  • 7
6

This code will assure to use your datepicker's format:

$('#date-selector').datepicker('setDate', new Date());

No need to re-apply format, it uses the datepicker predefined-one by you on datepicker initialization (if you have assigned it!) ;)

sth
  • 222,467
  • 53
  • 283
  • 367
Jeff Girard
  • 79
  • 1
  • 3
5

David K Egghead's code worked perfectly, thank you!

$(".date-pick").datepicker(); 
$(".date-pick").datepicker("setDate", new Date()); 

I also managed to trim it a little and it also worked:

$(".date-pick").datepicker().datepicker("setDate", new Date()); 
Jamie
  • 3,890
  • 3
  • 26
  • 35
Gary Medina
  • 51
  • 1
  • 2
4
$('input[name*="date"]').datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        beforeShow: function(input, instance) { 
            $(input).datepicker('setDate', new Date());
        }
    });
quocnguyen
  • 192
  • 2
  • 10
2

In order to set the datepicker to a certain default time (the current date in my case) on loading, AND then have the option to choose another date the syntax is :

    $(function() { 
        // initialize the datapicker
        $("#date").datepicker();

        // set the time
        var currentDate = new Date();
        $("#date").datepicker("setDate",currentDate);

    //  set the options for the button  
        $("#date").datepicker("option",{
            dateFormat: 'dd/mm',
            showOn: "button",
          // whatever option Or event you want 
        });
  });
maozx
  • 319
  • 4
  • 5
2

You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

Js:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                            }
                        }                         
                     );

Css:

div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
        div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active  {
            background: #1ABC9C;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            width: 24px; height: 24px;
        }​

OPTION B) Input by default with today. You've to populate first the datepicker .

$("input.datepicker").datepicker().datepicker("setDate", new Date());
chispitaos
  • 767
  • 9
  • 14
  • 1
    option A is good because date picker can remain blank until a date is to be selected at which point it defaults to the current date – waxingsatirical Jun 18 '18 at 12:48
1

Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:

    $( "#datepicker" ).datepicker();
    <?php if (!empty($oneEVENT['start_ts'])): ?>
       $( "#datepicker" ).datepicker( "setDate", "<?php echo $startDATE; ?>" );
    <? else: ?>
       $("#datepicker").datepicker('setDate', new Date());   
    <?php endif; ?>
  });
1

To pre-populate date, first you have to initialise datepicker, then pass setDate parameter value.

$("#date_pretty").datepicker().datepicker("setDate", new Date());
Nadir
  • 353
  • 2
  • 8
0

Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();
thejustv
  • 2,009
  • 26
  • 42
0

This works better for me as sometimes I have troubles calling .datepicker('setDate', new Date()); as it messes if if i have the datepicker already configured with parameters.

$("#myDateText").val(moment(new Date()).format('DD/MM/YYYY'));
Alpha2k
  • 2,212
  • 7
  • 38
  • 65
0
var prettyDate = $.datepicker.formatDate('dd-M-yy', new Date());
alert(prettyDate);

Assign the prettyDate to the necessary control.

sth
  • 222,467
  • 53
  • 283
  • 367
gmail user
  • 2,753
  • 4
  • 33
  • 42
0

Use This:

$(".datepicker").datepicker({ dateFormat: 'dd-M-yy' }).datepicker('setDate', new Date());

To Get Date in Format Eg: 10-Oct-2019 which will be more understandable for users.

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
nikhil
  • 56
  • 4
-1
$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html