Search code examples
javascriptdatepicker

Past and future date allow only 12 months from selected date


I use the bootstrap-datepicker library.

This screenshot shows a default pre-selected date:

enter image description here

My problem is that I can change the date to something like 2019-12-01, which is not within the specified range.

enter image description here

A future date can be changed to 2024-12-01.

enter image description here

I am expecting to be able to change the date only 12 months from the pre-selected date in past and future.

Here is my code:

$('#can_edit_doj').datepicker({
    format: "yyyy-mm-dd",
    autoclose: true,
    endDate: '+365d',
    startDate: '-365d
});

Solution

  • As CBroe pointed out in his comment, relative startDate and endDate values (like +365d) refer to the current date.

    Instead, you can use absolute values, calculated from your initial value.
    For example:

    const initialDate = new Date("2021/05/07");
    const dayRange = 365;
    const rangeInMillis = 1000 * 60 * 60 * 24 * dayRange;
    const startDate = new Date(initialDate.getTime() - rangeInMillis);
    const endDate = new Date(initialDate.getTime() + rangeInMillis);
    $("#can_edit_doj").datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
        startDate: startDate,
        endDate: endDate
    });
    $("#can_edit_doj").datepicker("setDate", initialDate);