Echo JS 0.11.0

<~>

tracker1 296 days ago. link 1 point
Worth noting, that adding a month the naive way won't always get you what you should expect... for example:

    let dtm = new Date(2020,0,31); // Fri Jan 31 2020...
    dtm.setMonth(dtm.getMonth() + 1);
    console.log(dtm);
    // Mon Mar 02 2020...

That's not what you should expect, I would expect the last day of February.

    function addMonths(dtm, months = 1) {
      const month = dtm.getMonth() + ~~months;
      const ret = new Date(dtm); // clone date - don't mutate
      ret.setMonth(month);
      if (ret.getMonth() > month) {
        ret.setDate(0); // go to end of previous month
      }
      return ret;
    }

This way you can add to the date, without mutation and get the expected result.

    let dtmIn = new Date(2020,0,31);
    let dtmOut = addMonths(new Date(2020,0,31));
    console.log(dtmOut);
    // Sat Feb 29 2020...