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