The solution you're looking for is something like this,
const twoWeeksAgo = 14 * 24 * 60 * 60 * 1000;
let dateElement = document.querySelector('#accident');
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
dateElement.max = new Date().toISOString().split('T')[0];
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
You can use the max and min attributes of the HTML5 date element (documented here) to restrict your element to only show certain values.
In this particular case, the min
attribute is set to the date (in yyyy-mm-dd
format) two weeks ago and the max
attribute is set to the current date.
The magic computation twoWeeksAgo
is the number of milliseconds in 14 days which will allow you to compute the date 14 days ago.
The code new Date(Date.now() - twoWeeksAgo)
gives us a Date object set to two weeks ago and the .toISOString()
function returns the date in YYYY-MM-DDTHH:mm:ss.sssZ
format, i.e., a date-time string.
Since the min
attribute only requires the date and not the time, we then split the obtained string using 'T' as a delimiter, which would give us the date in YYYY-MM-DD
format.
Putting it all together we get this line for the date two weeks ago
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
And similarly for the upper limit date,
dateElement.max = new Date().toISOString().split('T')[0];