Array of Dates of the Year

Asked

Viewed 829 times

1

In Javascript, how to work with a period spanning day, month and year at the same time and at once instead of using the New Date() getting 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, if the day has 30 or 31 days, etc.

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

I see you can declare a date like this:

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

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

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

That is possible?

  • You can use new Date(2010, 1, 0) and you will have the last day of January, and using new Date(2010, 1, -1) will give the previous day, ie 30 from January. That won’t do any good?

  • @Interesting, but I need to work based on the current day. I thought of something like this. var dataAntes = new Date()-4; var dataDepois = new Date()+3; I think it will work.

1 answer

1

The builder new Date 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 (from 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
  • 1

    Brilliant!!! Grateful!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.