简体   繁体   中英

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:

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

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
});

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM