0
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?

DanielG
  • 217
  • 2
  • 6
  • Does this answer your question? [How to subtract days from a plain Date?](https://stackoverflow.com/questions/1296358/how-to-subtract-days-from-a-plain-date) – codearn19 Dec 21 '22 at 17:04
  • Make `startDate` a copy of `endDate`, then subtract 2 days from its date. – Barmar Dec 21 '22 at 17:17

3 Answers3

1

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,
});
1

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

KaraX_X
  • 326
  • 2
  • 11
1

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.