Im having several issues using moment to calculate the difference in days. Let me expose my problem:
I have to subtract one date from todays date. For example 28/02/2022 - 21/02/2022. Doing this in this way:
const timeDifference = moment("28/02/2022", "DD/MM/YYYY").diff(moment(moment(), "DD/MM/YYYY"), "days");
This returns 6 days
as it doesnt include I believe the last day. Since I need it to include the last day I did the following:
const timeDifference = moment("21/02/2022", "DD/MM/YYYY")
.add(1, 'days')
.diff(moment(moment(), "DD/MM/YYYY"), "days");
This now returns 7
days which is what I need.
Now the problem is that I have an if statement
which does the following:
if (timeDifference < 0)
Now if timeDifference is todays date it returns 0 but if its 20/02/2022 it also returns 0 due to the .add when I need it to return -1.
I was now trying to do a different approach to do this if by doing
if (moment("20/02/2022") < moment.utc()) {
but this is not working when the date is less than todays date it will enter the if statement.
CodePudding user response:
I believe what you are looking for is this :
moment("28/02/2022", "DD/MM/YYYY").diff(moment().startOf('day'), 'days')
By the way, no need for that double moment() in the diff, ass diff
takes moment
instance what ever the source.