How To Add or Subtract Days, Weeks, Months and Years to a Date in JavaScript with date-fns
// import isn't supported in Node v18.11.0 otherwise it would be
// import { add, sub } from 'date-fns'
const dateFns = require( "date-fns");
const { add, sub } = dateFns;
// 31th of January 2023
const date = new Date(2023, 0, 31);
console.log(date);
console.log('Subtract 5 days, 2 months, 3 weeks and 7 years: ', sub(date, {
days: 5,
weeks: 3,
months: 2,
years: 7
}));
console.log('Add 5 days, 2 months, 3 weeks and 7 years: ', add(date, {
days: 5,
weeks: 3,
months: 2,
years: 7
}));
no comments