How To Add Months to a Date in JavaScript with date-fns
// import isn't supported in Node v18.11.0 otherwise it would be
// import { addMonths } from 'date-fns'
const dateFns = require( "date-fns");
const { addMonths } = dateFns;
// 31th of January 2023
const date = new Date(2023, 0, 31);
const leapYear = new Date(2024, 0, 31);
console.log(date);
console.log(leapYear);
console.log('Add 1 month: ', addMonths(date, 1));
console.log('Add 1 month to leap year: ', addMonths(leapYear, 1));
console.log('Add 3 months: ', addMonths(date, 3));
console.log('Add 9 months: ', addMonths(date, 9));
console.log(date);
no comments