3

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!

madth3
  • 7,275
  • 12
  • 50
  • 74
designtocode
  • 2,215
  • 4
  • 21
  • 35
  • I don't see an issue with how you're doing it. I've had a quick look at the available options and methods for that datepicker and it doesn't look like you can set a default date. – Mark Walters Jul 31 '13 at 08:07
  • I thought I was missing something, but looks like I'm not! Thanks @MarkWalters I'll just use this method. – designtocode Jul 31 '13 at 08:15

2 Answers2

4

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
Dziad Borowy
  • 12,368
  • 4
  • 41
  • 53
  • This looks great! I'll try this out and see how it works, it looks like it will reduce the amount of characters for getting the current date. – designtocode Jul 31 '13 at 10:30
3

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.