Reputation: 287
let startDate = new Date();
startDate.setDate(endDate.getDate() - 2);
I want to substract 2 days from endDate, and get the new date. this code works fine if we stay in the same month after subtraction. how can I substract days and get the currect date, even if a month or a year changed?
Upvotes: 0
Views: 48
Reputation: 106
You can use sub from date-fns to achieve this, like so:
import sub from 'date-fns/sub'
const result = sub(new Date(), {
days: 2,
})
In your case it would look like this:
import sub from 'date-fns/sub'
let startDate = sub(endDate, {
days: 2,
});
Upvotes: 1
Reputation: 114
You can substract by milliseconds like this.
let endDate = new Date();
let startDate = new Date();
startDate.setTime(endDate.getTime() - 2 * 1000 * 60 * 60 * 24);
I hope this will help you.
Upvotes: 1
Reputation: 453
getDate() is only return the actually date, so if you endDate is Oct 20, it will return you 20. you can either DO setYear() and setMonth() on the startDay as well. or you can just create a new date from endDate - 2. then assign to the startDate
Upvotes: 1