0

I want to add 90 days to the given start date, So I have this:

const start = new Date('2021-11-15T13:27:16.982Z');
const end = new Date().setDate(start.getDate() + (90));
       
console.log(getDate(start))
console.log(getDate(end))
      
function getDate(date) {
   return new Date(date).toLocaleDateString('en-US')
}

But As you notice instead of getting 90 days late it returns -2 days!

Why this is happening and how to fix this?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
Sara Ree
  • 3,417
  • 12
  • 48
  • this took a while to decipher ... `new Date().setDate(start.getDate() + (90));` is setting the date to 105, relative to today – Bravo Aug 10 '21 at 12:58
  • Does this answer your question? [Add days to JavaScript Date](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – Bravo Aug 10 '21 at 13:03

2 Answers2

1

use var time = new Date() instead, then follow the following steps

  • create a variable with the new Date()
  • then you will get something like this Tue Aug 10 2021 15:50:10 GMT+0300 (Arabian Standard Time)
  • after that split the time value by space (convert it to string first)
  • you will get ["Tue", "Aug", "10", "2021", "15:50:10", "GMT+0300", "(Arabian", "Standard", "Time)"] you can find the day on the 2nd index
  • now you can change with any of them, if you want to add to the days as you said, make it to int type then reassign it to the array
Kh4lid MD
  • 125
  • 1
  • 2
  • 10
1

This is what exactly you want: https://stackoverflow.com/a/19691491/11359076

look at this code const end = new Date().setDate(start.getDate() + (90));

The only time this answer works is when the date that you are adding days to happens to have the current year and month.

So use this way: const end = new Date(start).setDate(start.getDate() + 90)

const start = new Date('2021-11-15T13:27:16.982Z');

const end = new Date(start).setDate(start.getDate() + 90);
  
  
console.log(getDate(start))
console.log(getDate(end))
  
  
function getDate(date) {
   return new Date(date).toLocaleDateString('en-US')
}
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42