tl; dr :
The most correct is something like this:
inicial = new Date(ano, mes, dia);
milissegundos_por_dia = 1000 * 60 * 60 * 24;
data_final = new Date(inicial.getTime() + dias * milissegundos_por_dia);
explaining :
The Date
object has some convenient methods to access each type of value associated with the date it contains.
The .getDate
method in particular retrieves the day of the month as an integer. The problem with wanting to subtract dates using getDate()
is when you reach the "borders" of a month: it's okay if it's day 15 and you want the date 2 days ago - getDate()
returns 15, you take 2, has 13, makes a setDate
, and has the correct date of 2 days ago.
The problem is if you are on the 7th and want the date 15 days ago. Or just want the date 30 days ago. Using getDate, you would have to make a structure of if
and else
for when the desired day of the month was negative, subtract one from the month, and then set the day accordingly. And another if
for the case of the month that came back from January to December, in which case, subtract the year.
Not to mention the numerous corner-cases, such as leap times, start and end of daylight saving time, etc. ... may seem trivial at first, but it's always nice to keep in mind that Microsoft itself, in early versions of Excel, missed the calculation of dates for the year 1900 (treating it as a leap, since it was not - and to this day the date format encoded in .XLS files suffers because of this error).
Fortunately, the Date
object also has methods getTime
and setTime
, which instead of saying a date as month, day, year, hours, minutes, and seconds in separate fields, returns (and accepts) a single integer: The number of milliseconds since midnight 1/1/1970.
This representation derives from the so-called "unixtime" used in servers and programs worldwide - which represents the number of seconds passed since the same date. (see in Javascript, we have the milliseconds, not the seconds).
So, given a date, all we have to do to calculate the subtraction (or addition) of a certain number of days is to use
.getTime
, manipulate that number, and use
.setTime
or create a new object
Date
to obtain the values "usable by human", month, day and year, of the desired date.
That is:
...
ano = ...;
mes = ...;
dia = ...;
...
dias = ...;
...
inicial = new Date(ano, mes, dia);
milissegundos_por_dia = 1000 * 60 * 60 * 24;
data_final = new Date(inicial.getTime() + dias * milissegundos_por_dia);
And ready - you have the final date with no problem of month calculation, year-round, leap second - you reuse all the thousands of lines of code that are in the browser and operating system to calculate the date without needing reinvent the wheel.