How can I set the min and max attributes of a date input within a (dynamic) range?

Hello :slight_smile:

I have some code like this:

<!-- value & min should be today -->
<input type="date" id="listingDateOpen">
<!-- min should be Open Date's value, value & max should be 1 month from that date-->
<input type="date" id="listingDateClose">
let today = new Date(),
    day = today.getDate(),
    month = today.getMonth()+1, //January is 0
    year = today.getFullYear();
        today = year+'-'+month+'-'+day;

        document.getElementById("listingDateOpen").setAttribute("min", today);
        document.getElementById("listingDateOpen").setAttribute("value", today);

I’ve got the Open Date input to have a default value and min set to today’s date…works perfectly. However, I am struggling with the Close Date input.

I’d like the min attribute for the Close Date input set to the Open Date’s current value. And it’s max value should be set to 1 month’s time from that date.

For example, If a user selects 12th November 2018 in the Open Date, then the min value for Close Date should be 12th November 2018, and the max value should be 12th December 2018.

Kindly guide me through this process…

Here is my attempt, but it does not set the max date…:

       let openDate
            openDate = $("#listingDateOpen").val();
            let maxCloseDate = new Date(openDate);
            document.getElementById("listingDateClose").setAttribute("min", openDate);
            document.getElementById("listingDateClose").setAttribute("value", openDate);
            maxCloseDate.setMonth(maxCloseDate.getMonth() + 1);
            document.getElementById("listingDateClose").setAttribute("max", maxCloseDate);

You might want to look at moment.js if your working with date differences. The library makes this really easy. Just get the diff then check if it’s greater than your max date, if it’s less great if not let the user know.

var now = moment(new Date()); //todays date
var end = moment("2018-12-12"); // another date
var duration = moment.duration(now.diff(end));
var days = duration.asDays();
    if (days > 30) {
        console.log('bad news here');
    } else {
        console.log('good news here');