Reputation: 299
Im building a filter in node.js and i need to loop through months in a given daterange and get the first and last days of said month
every attempt i make at this after the first few months the dates start getting off
Example of results looping through 1 year
2019-01-01 2019-01-31
2019-02-01 2019-02-28
2019-03-01 2019-03-31
2019-03-31 2019-04-29
2019-04-30 2019-05-30
2019-05-31 2019-06-29
2019-06-30 2019-07-30
2019-07-31 2019-08-30
2019-08-31 2019-09-29
2019-09-30 2019-10-31
2019-11-01 2019-11-30
2019-12-01 2019-12-31
by the end it seems to get back the dates
Any ideas?
Upvotes: 0
Views: 253
Reputation: 1691
They go off because of day lights saving time. Just pass in the hour as well when you create the date.
for(let a=0;a<12;a++)
{
let year = new Date().getFullYear()
let firstDay = new Date(Date.UTC(year, a , 1));
let lastDay = new Date(Date.UTC(year, a + 1, 0));
document.body.innerHTML += `<div>${firstDay.toISOString().substring(0, 10)} - ${lastDay.toISOString().substring(0, 10)}</div>`;
}
Output
2019-01-01 - 2019-01-31
2019-02-01 - 2019-02-28
2019-03-01 - 2019-03-31
2019-04-01 - 2019-04-30
2019-05-01 - 2019-05-31
2019-06-01 - 2019-06-30
2019-07-01 - 2019-07-31
2019-08-01 - 2019-08-31
2019-09-01 - 2019-09-30
2019-10-01 - 2019-10-31
2019-11-01 - 2019-11-30
2019-12-01 - 2019-12-31
**Update
As per RobG suggestion below. Edited to remove timezone offsets altogether.
Upvotes: 1