Line in Linus
Line in Linus

Reputation: 420

Bootstrap Datetimepicker wrong default date with minDate

I'm using Eonasdan Bootstrap Datetimepicker: http://eonasdan.github.io/bootstrap-datetimepicker/

Although I can't get the minDate and maxDate to work as expected. Since the date is dynamic and changes the fiddle is set upp with moments.js´ subtract/add

Conditions

minDate = today + 1 day
maxDate = today + 3 days
default value = today + 2 days

The above returns the value tomorrow and not the default value. If minDate is changed to -2 days it works just fine.

See Fiddle: http://jsfiddle.net/9uqpu88v/8/

twoDaysFromToday =  moment().add(2, 'd').format('YYYY-MM-DD');

$('#datetimepicker1 input').val(twoDaysFromToday); 
      var datetimepicker = $('#datetimepicker1').datetimepicker({
      format: 'YYYY-MM-DD',
      minDate: moment().add(1, 'd').format('YYYY-MM-DD'), // Tomorrow
      maxDate: moment().add(3, 'd').format('YYYY-MM-DD'), // Three days from today
    })


<div class="form-group">
  <div class="input-group date" id="datetimepicker1">
    <input type="text" id="datetimepicker1" class="form-control" value="" />    
    <span class="input-group-addon"><span class="glyphicon-calendar glyphicon"></span></span>
  </div>
</div>

Upvotes: 0

Views: 3514

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You can pass moment object instead of string to minDate and maxDate. Use defaultDate option to set the value to your picker instead of jQuery val(). Note that the library provides also a date method to set value to the component.

Use moment startOf to be hour independent.

Here a working example:

var datetimepicker1 = $('#datetimepicker1').datetimepicker({
  format: 'YYYY-MM-DD',
  useCurrent: false,
  defaultDate: moment().startOf('day').add(2, 'd'),
  minDate: moment().startOf('day').add(1, 'd'),
  maxDate: moment().startOf('day').add(3, 'd')
})
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
  <div class="input-group date" id="datetimepicker1">
    <input type="text" class="form-control" />
    <span class="input-group-addon"><span class="glyphicon-calendar glyphicon"></span></span>
  </div>
</div>

Upvotes: 2

Related Questions