Add and Subtract day, month, year in Javascript Date

Date and Time modification is a very common part of development. In Javascript add or subtract different date parameters is as easy as other languages. We have explained different addition and Subtraction with the example below:

Add or Subtract Days:

const date = new Date();
const additionOfDays = 10;
date.setDate(date.getDate() + additionOfDays); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Mon Mar 09 2020 13:50:56 GMT+0530 (India Standard Time)

 

Add or Subtract Months:

const date = new Date();
const additionOfMonths = 2;
date.setMonth(date.getMonth() + additionOfMonths); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Tue Apr 28 2020 13:52:52 GMT+0530 (India Standard Time)

 

Add or Subtract Years:

const date = new Date();
const additionOfYears = 10;
date.setFullYear(date.getFullYear() + additionOfYears); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Thu Feb 28 2030 13:55:16 GMT+0530 (India Standard Time)

 

Add or Subtract Hours:

const date = new Date();
const additionOfHours = 10;
date.setHours(date.getHours() + additionOfHours); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Fri Feb 28 2020 23:56:37 GMT+0530 (India Standard Time)

 

Add or Subtract Minutes:

const date = new Date();
const additionOfMinutes = 10;
date.getMinutes(date.getMinutes() + additionOfMinutes); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Fri Feb 28 2020 13:57:40 GMT+0530 (India Standard Time)

 

Add or Subtract Seconds:

const date = new Date();
const additionOfSeconds = 10;
date.setSeconds(date.getSeconds() + additionOfSeconds); // For subtract use minus (-)
console.log('New Date:', date);

Output: New Date: Fri Feb 28 2020 13:59:33 GMT+0530 (India Standard Time)

 

Keywords: