Borislav Hadzhiev
Fri Jan 21 2022·2 min read
Photo by Roi Dimor
To subtract years from a date:
getFullYear()
method to get the year of the specific date.setFullYear()
method to set the year for the date.setFullYear
method takes a number representing the year as a parameter
and sets the value for the date.function subtractYears(numOfYears, date = new Date()) { date.setFullYear(date.getFullYear() - numOfYears); return date; } // 👇️ subtract 1 year from current Date const result = subtractYears(1); // 👇️ Subtract 2 years from another Date const date = new Date('2022-04-26'); // 👇️ Sun Apr 26 2020 console.log(subtractYears(2, date));
We created a reusable function that takes the number of years and a Date
object as parameters and subtracts the years from the date.
Date
object is provided to the function, it uses the current date.We used the getFullYear method to get the year of the given date.
The setFullYear method takes an integer that represents the year as a parameter and sets the value on the date.
setFullYear
method mutates the Date
object it was called on. If you don't want to change the Date
in place, you can create a copy of it before calling the method.function subtractYears(numOfYears, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setFullYear(dateCopy.getFullYear() - numOfYears); return dateCopy; } const date = new Date('2022-04-27'); const result = subtractYears(3, date); console.log(result); // 👉️ Sat Apr 27 2019 console.log(date); // 👉️ Wed Apr 27 2022 (didn't change original)
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
Date
object, so we don't mutate it in place when calling the setFullYear
method.Copying the date is quite useful when you have to use the original Date
object
in other places in your code.