If you want the difference in days, just change to moment().diff(date, 'days')
.
Already about "calculate forward and not backward", you mean that instead of calculating data_atual - date
, you want to date - data_atual
?
If that’s the case, just reverse the signal:
onCalcularData(date: any): number {
return -moment().diff(date, 'days');
}
I put the minus sign (-
), what "reverses" the return. After all, if the date
represent, for example, a date 10 days before the current date, the difference between them in days will always be 10, and the only thing that changes when reversing the order in which the subtraction is made will be the sign.
Of course you can also reverse the dates in the calculation:
onCalcularData(date: any): number {
return moment(date).diff(moment(), 'days');
}
The difference is I had to moment(date)
, for date
was declared as any
(i.e., it can be "anything"), so it will not necessarily be a moment
. In doing moment(date)
, I guarantee she will be converted to a moment
and I can use the method diff
.
In your code that wasn’t necessary because according to the documentation, the method diff
accepts "anything" as a parameter (a moment
, one string
, one Date
, etc) and internally it converts it to moment
, so you can pass the date
directly to diff
. But if you want to "reverse", you need to turn it into a moment
.
Another alternative, if you want only the number of days between the dates, regardless of whether one date is in the future or in the past in relation to the other, may also:
onCalcularData(date: any): number {
return Math.abs(moment().diff(date, 'days'))
}
Thus, whether the result is a positive or negative number, the function returns the number of days between the two dates without the sign (whether the difference is -10 or 10, the function will return 10).
But if the sign is important, you should choose the order that makes the most sense for your case, and not use Math.abs
.
But there’s a detail there. The calculation also takes into account the time, and the difference in days is rounded down (for example, between 10h today and 9h tomorrow, the difference is zero days - only from 10h tomorrow is that the difference gives 1). And the current date (moment()
) will always have the time when she was created.
One way to skip the time is to set both dates to the same time. An alternative is to use startOf('day')
to set them for the start of the day:
onCalcularData(date: any): number {
return Math.abs(moment().startOf('day').diff(moment(date).startOf('day'), 'days'));
}
tries date.diff(Moment(), 'years');
– Eduardo Vargas