To add a certain amount of days to a date, just use add
:
onCalcularData(date: any, dias: number): moment.Moment {
return moment(date).add(dias, 'days');
}
The return will be a Moment
. But if you want to return one Date
, just use toDate()
:
onCalcularData(date: any, dias: number): Date {
return moment(date).add(dias, 'days').toDate();
}
So, if you run with the current date (08/07/2020) and add 14 days (onCalcularData(new Date(), 14)
), the result will be 22/07/2020. Remembering that the time will be kept (for example, it is now 8:12 in the morning, so the final result will be 22/07 at the same time).
Taking advantage, I think it is worth explaining two important concepts: dates and durations.
A date is a specific point in the calendar. For example, 08/07/2020 represents the 8th day of month 7 of year 2020 of the Gregorian calendar.
A duration is a amount of time. For example, "14 days" - represents only a period, any amount of time, but without any relation to the calendar (the duration exists by itself, if I say only "14 days", it is not possible to know when it started or ended).
What can be confusing is the fact that they both use the same words ("day", "month", etc), but they are different things.
But these two concepts are related. The difference between two dates is a duration (between days 8 and 22, the difference - or the duration between those dates - is 14 days).
And if I add a date with a duration, the result is another date (day 8 + duration 14 days = day 22).
The question code uses diff
, that calculates the difference between two dates and returns a duration. But you wanted to add a duration and a date, and that’s why add
serves.
Complementing, if the idea is to add at all times from the current date, it would look like this:
onCalcularData(dias: number): moment.Moment {
return moment().add(dias, 'days');
}
Your question is confused. Give an example of input, expected output and current output.
– Rafael Tavares
Oi Rafael - following your proposal, I need to take the current date and fill in an input a decimal value, for example: Current date: 08/07/2020 + Input (input value): 14 = expected output 22/07/2020. Today I calculate by taking two dates and turning them into days
– fernanda