Search code examples
jquerydatedatetimepicker

How to set end date greater the start date using jquery date time picker


Am using jquery date time picker set an event's start and end dates.But how can I prevent to select event end date should greater than event start date. I end date selected first then start date should be less than end date.

I have tried using the following code,but didn't worked for me:

    $('#startDate').datetimepicker({
        dayOfWeekStart : 1,
        lang:'en',
        minDate: new Date(),
        onSelect: function(dateText, inst){ 
          $("#endDate").datetimepicker('option', 'minDate', dateText);
       }  
    });

    $('#endDate').datetimepicker({
        dayOfWeekStart : 1,
        lang:'en',
        startDate:  new Date(),
        onSelect: function(dateText, inst){
          $("#startDate").datetimepicker('option', 'maxDate', dateText);
       }
    });

And my html for the page is like:

   <form action="" method="POST">
    <div class="col-sm-2 col-lg-2">
        <div class="form-group "> 
            <input type="text" value="" id="startDate" name="startDate" class="form-control" autocomplete="off" placeholder="Start Date"/>

        </div>
        <div class="form-group "> 
            <input type="text" value="" autocomplete="off" id="endDate" name="endDate" class="form-control" placeholder="End Date"/>

        </div>
        <div class="form-group "> 
            <input type="text" value="" name="eventName" class="form-control" placeholder="Event Name"/>

        </div>
            <input type="submit" name="submit" value="Add Event" class="btn btn-primary">
    </div>
</form>

Solution

  • Check data difference of start & end date when end date is selected and can try this..

    $('#endDate').datetimepicker({
        dayOfWeekStart : 1,
        lang:'en',
        startDate:  new Date(),
        onSelect: function(dateText){
            var start_date = new Date($('#startDate').val()),
                end_date = new Date(dateText),
                diff  = new Date(end_date - start_date),
                days  = parseInt(diff/(1000*60*60*24), 10);
            if(days < 1){
                alert('End date should be greater than start date!')
                $(this).val('');
                return false;
            }
            //$("#startDate").datetimepicker('option', 'maxDate', dateText);
    
        }
    });
    

    You can also apply this date difference scripts for start date selection.