Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datepicker: Setting input value to current date

I am using this plugin for Bootstrap, for date picking http://eternicode.github.io/bootstrap-datepicker/

I have it working here FIDDLE But I dont know if this is the right way to do it? Or if there's a way to do it through the plugin. I've tried to but I haven't got it right.

HTML:

Date: <input type="text" name="" class="datepicker" />

Jquery:

var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output =((''+month).length<2 ? '0' : '') + month +  '/' + ((''+day).length<2 ? '0' : '') + day + '/' + d.getFullYear();

$('.datepicker').datepicker();

$('.datepicker').val(output);

So I'm using Jquery to get the current date then I just fire the datepicker and then set the input value to the current date.

Any other ideas or suggestions will be appreciated!

like image 511
designtocode Avatar asked Aug 17 '26 13:08

designtocode


2 Answers

Your method is good.

You could, however, reduce it a couple of characters - if you'd like - to something like this:

var d = new Date(),
    output = [
        ('0' + (d.getMonth() + 1)).substr(-2), 
        ('0' + d.getDate()).substr(-2), 
        d.getFullYear()
    ].join('/');

$('.datepicker').datepicker().val(output);

Also - if you're doing more work with dates - it might be a good idea to have a look at some date libraries, like date.js or sugar.js, then you could do something like this:

$('.datepicker').val(new Date().toString('MM/dd/yyyy'));        // date.js
$('.datepicker').val(Date.create().format('{MM}/{dd}/{yyyy}')); // sugar.js
like image 100
Dziad Borowy Avatar answered Aug 19 '26 02:08

Dziad Borowy


Datepicker is initialized with current date by default. (demo)

You can set it manually too:

$("#datepicker").datepicker({defaultDate: new Date()}); //at initialization
$("#datepicker").datepicker("setDate",new Date());      //runtume

Setting to other dates is easy too:

$("#datepicker").datepicker("setDate","14/12/2014");

With self defined format:

$("#datepicker").datepicker({ dateFormat: "yy-m-d" });
$("#datepicker").datepicker("setDate","14-12-4");

To get that formatted value, use:

$("#datepicker").datepicker().val();

Documentation here.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!