How to get the previous year in JavaScript
In this tutorial, we are going to learn about how to get the previous year from the current date using JavaScript.
Getting the previous year
To get the previous year in JavaScript, first we need to access the current year by calling a getFullYear()
method on new Date()
constructor and subtract it with -1
.
The
getFullYear()
method returns the current year in four-digit(2020) format according to the user local time.
Here is an example:
const currentYear = new Date().getFullYear(); // 2024
const previousYear = currentYear-1;
console.log(previousYear); // 2023
If you want to set a previous year to the current date, you can do it like this:
const d = new Date();
d.setFullYear(d.getFullYear()-1);
console.log(d.toDateString()); // "Sat Mar 02 2023"