Adding days to a Date object in JavaScript is not working properly

Viewed 196

I have read several questions on stack overflow and all over the internet but somehow I am unable to get it right. I get a date from another function and the value is as below.

var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)

// want to add 45 days to my date
var offset = 45;
var xDate = new Date();
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);

The output I get is:

Mon Jul 12 2021 19:00:57 GMT+1000 (Australian Eastern Standard Time)

where as this should be some date in June.

Please can someone help me understand what I am doing wrong?

5 Answers

The problem is that when you are initializing a new date object using new Date(), the date object is initialized with the current date. When you increment the days using currentDate.getDate() + offset the day of the month is first set to that of currentDate and incremented by offset but the month from which it is incremented is the current month. Try this one.

var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)

// want to add 45 days to my date
var offset = 45;
var xDate = new Date("2021-04-27T15:30:27.588+0000");
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);

1 day is equal to 86,400,000 milliseconds. You can multiply that value by 45 and add it to your date:

var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate);

// Add 45 days
var offset = 45;
var xDate = new Date(currentDate.getTime() + offset * 86400000);
console.log(xDate);

My suggestion:

const addDays = (date, days) => {
  var ndt = new Date(date);
  ndt.setDate(date.getDate() + days);
  return ndt;
};

var date = new Date("2021-04-27T15:30:27.588+0000");

console.log(date);
console.log(addDays(date, 45));

I agree Wais Kamal's answer is right. The below code is more succinct since you avoid time calculations

var currentDate = new Date("2021-04-27T15:30:27.588+0000");
var offset = 45;
var xDate = currentDate.setDate(currentDate.getDate() + offset);
console.log(xDate);

You can make use of the moment here. Link to official docs. Don't forget to install moment package like so (assuming you are using npm)

npm i moment
  const myDate = "2021-04-27T15:30:27.588+0000";
  const updatedDate =  moment
          .utc(myDate)
          .add(45, 'days')
          .format('YYYY-MM-DD');
    
  console.log('updatedDate', updatedDate); // "2021-06-11"

Related