designtocode
designtocode

Reputation: 2245

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!

Upvotes: 3

Views: 37897

Answers (2)

user669677
user669677

Reputation:

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.

Upvotes: 3

Dziad Borowy
Dziad Borowy

Reputation: 12589

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

Upvotes: 4

Related Questions