1

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.

mmz
  • 1,011
  • 1
  • 8
  • 21

1 Answers1

1

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;
}
some coder guy
  • 285
  • 3
  • 10
  • 3
    Using `new Date(string)` with some formats is risky and browser-, OS-, and locale-specific. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – Heretic Monkey Aug 24 '21 at 17:30
  • @HereticMonkey good to know, thanks. – some coder guy Aug 24 '21 at 17:34
  • 1
    `new Date(Date.parse(dateString))` will produce an identical result to `new Date(dateString)`, so the call to *Date.parse* is redundant. But you shouldn't be parsing unsupported formats with the built–in parser anyway, per @HereticMonkey's comment. – RobG Aug 24 '21 at 22:19