Set maxDate in the datepicker using Moment

Depending on the year selected in the dropdown, I need to set the date picker minDate and MaxDate. MinDate can only be Jan/01/{selectedYear} and MaxDate should be Dec/01/{selectedYear}

I tried below. But doesn’t seem to work:

MinDate = moment().format(`01/01/${selectedYear}`);
MaxDate = moment().format(`02/01/${selectedYear}`);

Output looks like:

MinDate 01/01/2020 & MaxDate 02/01/2020

9 thoughts on “Set maxDate in the datepicker using Moment”

  1. I don’t get your point.
    Can you please provide us your code? or maybe in a snippet or something.

    And also, should MinDate & MaxDate be strings or Dates?


    Do you want the output to be as follwing?

    if selected year = 2020

    MinDate: Jan/01/2020 & MaxDate: Dec/01/2020

    if so, then you need to use this:

    let selectedYear = 2020; //or "2020"
    
    //using moment
    let minDate = moment().month(0).format(`MMM/01/${selectedYear}`); //you can also manipulate the day via moment
    let maxDate = moment().month(11).date(1).format(`MMM/DD/${selectedYear}`);
    
    console.log('minDate: ', minDate);
    console.log('maxDate: ', maxDate);
    
    
    //although you can do the stuff above without Moment:
    let minDate0 = `Jan/01/${selectedYear}`;
    let maxDate0 = `Dec/01/${selectedYear}`;
    
    console.log('minDate (without moment): ', minDate0);
    console.log('maxDate (without moment): ', maxDate0);
    <script src="https://momentjs.com/downloads/moment.js"></script>
    Reply

Leave a Comment