1 | initial version |
Here is one way to retrieve the name of the previous month from an array in Reactjs:
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
const currentDate = new Date();
const currentMonthIndex = currentDate.getMonth();
const previousMonthIndex = currentMonthIndex - 1;
Note: If the current month is January, the previous month will be December of the previous year.
let previousMonthName = '';
if (previousMonthIndex < 0) {
// If previousMonthIndex is negative, set it to December of previous year
previousMonthIndex = 11; // December
currentDate.setFullYear(currentDate.getFullYear() - 1);
}
if (previousMonthIndex > 11) {
// If previousMonthIndex is greater than 11, set it to January of next year
previousMonthIndex = 0; // January
currentDate.setFullYear(currentDate.getFullYear() + 1);
}
previousMonthName = months[previousMonthIndex];
return <div>Previous month: {previousMonthName}</div>;
This code will retrieve the name of the previous month from an array in Reactjs.