Jquery Ui date time picker

Srinath Murugula picture Srinath Murugula · May 22, 2015 · Viewed 22.8k times · Source

I am using jquery date time picker and using start date and end date.

When selecting same date for start date and end date I do not want it to allow the end date time to be less than start date time. How would I adjust my code?

$( "#fdate" ).datetimepicker({
     dateFormat: 'yy-mm-dd',timeFormat: 'HH:mm:ss',
        onClose: function( selectedDate ) {
        $( "#tdate" ).datetimepicker( "option", "minDate", selectedDate );
  }
  }).attr('readonly', 'readonly');
     $( "#tdate" ).datetimepicker({dateFormat: 'yy-mm-dd',timeFormat: 'HH:mm:ss',
  onClose: function( selectedDate ) {
     $( "#fdate" ).datetimepicker( "option", "maxDate", selectedDate );
  }
  }).attr('readonly', 'readonly');
});

here fdate is start date and tdate is end date and here is Fiddle of the issue

Answer

JasonWilczak picture JasonWilczak · May 22, 2015

You need to use the 'setOptions' method for each timepicker:

$(document).ready(function(){
    $("#fdate" ).datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'HH:mm:ss',
        onShow: function () {
            this.setOptions({
                maxDate:$('#tdate').val()?$('#tdate').val():false,
                maxTime:$('#tdate').val()?$('#tdate').val():false
            });
        }
  }).attr('readonly', 'readonly');
  $( "#tdate" ).datetimepicker({
      dateFormat: 'yy-mm-dd',
      timeFormat: 'HH:mm:ss',
        onShow: function () {
            this.setOptions({
                minDate:$('#fdate').val()?$('#fdate').val():false,
                minTime:$('#fdate').val()?$('#fdate').val():false
            });
        }                    
  }).attr('readonly', 'readonly');    

Here is the Modified Fiddle.

This is not perfect, but it will get you close, you may need to handle some of the formatting. I used the 'onShow' event, but you could easily do it in the onClose, as well. There is a small sample on their official page called Range between date#.