How to do date rounding in Javascript? [closed]

I have an array of dates that I want to round to various frequencies – weeks, months, quarters, and years. The equivalent of rounding numbers but for dates.

Here is a sample array:

const dates = [
  "1/4/2020",
  "2/5/2021",
  "8/15/2021",
];

Rounding by month would yield:

[
  "1/31/2020",
  "2/28/2021",
  "8/31/2021",
];

Nearest year:

[
  "12/31/2020",
  "12/31/2021",
  "12/31/2021",
];

And so on. Is there a Javascript library that allows for such rounding? If not, is there a simple function that would cover the above frequencies? I can write a custom function for each use case but that’ll likely be inefficient.

Answer

Assuming there is a typo in your first array of dates and “2/5/2020” was meant to be “2/5/2021” (which would explain your desired results), this code should work:

function roundMonth(dateString) {
  var date = new Date(Date.parse(dateString));
  var year = date.getFullYear();
  var month = date.getMonth();
  var date = new Date(year, month + 1, 0); 
    // day 0 yields the last day of the previous month, 
    // so we add 1 to the month value
  var year = date.getFullYear();
  var month = date.getMonth();
  var day = date.getDate();
  var date = [month + 1,day,year].join("/");
    // for string output we add 1 to month since Jan is month 0
  return date;
}

function roundYear(dateString) {
  var date = new Date(Date.parse(dateString));
  var year = date.getFullYear();
  var date = [12,31,year].join("/");
  return date;
}