user3773893
user3773893

Reputation: 7

Setting max date value to current date OR 1 year from start date

What should I do to restrict the user to select the end date beyond one year from the starting date OR the current date. I have my codes like this.

$(function () {
$('#DateFrom').datepicker({
    dateFormat:'d-M-y',
    changeMonth: true,
    changeYear: true,
    minDate: new Date(2000, 7, 23), 
    maxDate: 0,
    onSelect: function() {
        var date = $('#DateFrom').datepicker('getDate');
        date.setTime(date.getTime() + (1000*60*60*24*365));
        $('#DateTo').datepicker('option', 'maxDate', date);
        $('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
        displayToUser();
    },

});

$('#DateTo').datepicker({
    dateFormat:'d-M-y',
    maxDate: 0,
    changeMonth: true,
    changeYear: true,
    onSelect: displayToUser,
});
});
function displayToUser() {}

Here although it restricts the user within one year from starting date, but it allows the user to select dates beyond the current date.

Example: if start date is 23-01-2016, it allows to select the end date upto 22-01-2017. I want it to be at most today's date.

Upvotes: 0

Views: 2951

Answers (1)

Aaron
Aaron

Reputation: 404

Does this do it?

$(function () {
    $('#DateFrom').datepicker({
        dateFormat:'d-M-y',
        changeMonth: true,
        changeYear: true,
        minDate: new Date(2000, 7, 23), 
        maxDate: 0,
        onSelect: function() {
            var date = $('#DateFrom').datepicker('getDate');
            date.setTime(date.getTime() + (1000*60*60*24*365));
            var todaysDate = new Date();
            if(date.getTime() > todaysDate.getTime()) date = todaysDate;
            $('#DateTo').datepicker('option', 'maxDate', date);
            $('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
            displayToUser();
        },

    });

    $('#DateTo').datepicker({
        dateFormat:'d-M-y',
        maxDate: 0,
        changeMonth: true,
        changeYear: true,
        onSelect: displayToUser,
    });
});
function displayToUser() {}

I only added these two lines

            var todaysDate = new Date();
            if(date.getTime() > todaysDate.getTime()) date = todaysDate;

Upvotes: 1

Related Questions