Search code examples
javascriptdatedatetimedatetimepickerdate-range

Calculate date range using javascript


I use a date/time picker to select date and time:

var d = new Date();

$('#timePicker').datetimepicker({
    dateFormat: 'dd-mm-yyyy',
    timeFormat: 'hh:mm',
    separator: '@',
    minDate: new Date(),
    maxDate: new Date(),
});

minDate and maxDate define the date range. No dates in the past should be selected, so the current date is the lower bound.

The upper bound should be max 2 month in the future. So how do I handle that when current month is 11? Any ideas on a function that calculates date range?


Solution

  • var d = new Date(); // initially contains current date
    var e = new Date(); // initially contains current date
                        // note: both dates must initially contain same value
    e.setMonth(d.getMonth() + 2);
    console.log(d);    
    console.log(e);
    

    Replace console.log with alert if necessary. This will work for dates in November and December in case you're wondering.