How to add days to a date with Moment.js?

I'm trying to calculate the term of my site in days, i.e. I put "14 days" and it turns into 00/00/0000.

I'm doing this way, but she's taking the full date and turning it into days, I want to do it the other way around, for example:

Current date: 07/08/2020 + input (input value): 14 = expected output 07/22/2020.

onCalcularData(date: any): number {
    return Math.abs(
      moment()
        .startOf('day')
        .diff(moment(date).startOf('day'), 'days'),
    );
  }

How to get to that?

Author: Rafael Tavares, 2020-07-07

1 answers

To add a certain amount of days to a date, simply 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 a Date, just use toDate():

onCalcularData(date: any, dias: number): Date {
    return moment(date).add(dias, 'days').toDate();
}

Thus, 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 08: 12 in the morning, then 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 8 day of the 7 month of the 2020 year of the Gregorian calendar.

A duration is an 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", you can't tell when it started or finish).

What can confuse is the fact that they both use the same words ("day"," month", etc.), but they are different things.

Only these two concepts are related. The difference between two dates is a duration (between days 8 and 22, the difference - or duration between these dates - is 14 days).

And if I add a date with a duration, the result is another date (Day 8 + 14-day duration = day 22).

The question code uses diff, which calculates the difference between two dates and returns a duration. But you wanted to add a duration and a date, and that's what add is for.


Complementing, if the idea is to add always from the current date, then it would look like this:

onCalcularData(dias: number): moment.Moment {
    return moment().add(dias, 'days');
}
 5
Author: hkotsubo, 2020-07-08 14:17:47