Skip to content
Advertisement

adding days to given date wired behavior

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?

Advertisement

Answer

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')
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement