Dates Array of the Year

1

In JavaScript, how do you work with a period spanning day, month, and year at the same time and at one time instead of using New Date () to get day, month and year individually and creating rules?

The idea is to work with a range of dates to do a certain task, without leap year formulas, whether the day is 30 or 31 days, etc.

If we can store all the days of the year in an array, it's easy to say that I want a certain mass of data to span data-3 and date + 7 more easily, for example.

I've seen how to declare a date like this:

var data = new Date(year,month,date);

But it does not work as a dynamic variable that can work in a range of days related to the month and the year.

Example: What date comes before 01/09/2017? If I use date-1 it would know that the previous day would be 08/31/2017, and so on.

Is this possible?

    
asked by anonymous 01.09.2017 / 22:17

1 answer

1

The new Date constructor allows larger and smaller numbers than "valid" dates. So you can always start from a given day and go forward or backward.

Example:

function dateToString(d) {
  return [d.getFullYear(), d.getMonth() + 1, d.getDate()].map(d => d > 9 ? d : '0' + d).join('-');
}

var hoje = new Date();
var ano = hoje.getFullYear();
var mes = hoje.getMonth();
var dia = hoje.getDate();
for (var i = -10; i < 10; i++) {
  var outroDia = new Date(ano, mes, dia + i);
  console.log(dateToString(outroDia));
}

This will print (as of today):

2017-08-22
2017-08-23
2017-08-24
2017-08-25
2017-08-26
2017-08-27
2017-08-28
2017-08-29
2017-08-30
2017-08-31
2017-09-01
2017-09-02
2017-09-03
2017-09-04
2017-09-05
2017-09-06
2017-09-07
2017-09-08
2017-09-09
2017-09-10
    
01.09.2017 / 22:37