PASSWORD RESET

Your destination for complete Tech news

How to get the previous month from a date in Javascript?

4.91K 0
< 1 min read

You can get the previous month from a date in JavaScript by using the Date object and its methods. Here is an example code snippet:

// Create a new Date object for the current date
const currentDate = new Date();

// Get the month and year of the current date
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();

// Calculate the month and year of the previous month
let previousMonth = currentMonth - 1;
let previousYear = currentYear;

if (previousMonth < 0) {
  // If the previous month is negative, subtract 1 from the year and set the month to 11 (December)
  previousMonth = 11;
  previousYear -= 1;
}

// Create a new Date object for the first day of the previous month
const previousMonthDate = new Date(previousYear, previousMonth, 1);

console.log(previousMonthDate.toLocaleString('default', { month: 'long' })); // Output: January

In this example, we first create a new Date object for the current date using the Date() constructor without any arguments, which creates a Date object for the current date and time.

We then get the month and year of the current date using the getMonth() and getFullYear() methods on the currentDate object.

Next, we calculate the month and year of the previous month by subtracting 1 from the current month. If the result is negative, we subtract 1 from the year and set the month to 11 (December) to get the previous December.

Finally, we create a new Date object for the first day of the previous month by passing in the previousYear, previousMonth, and 1 as arguments to the Date() constructor. We can then use the toLocaleString() method on the previousMonthDate object to get the name of the previous month. In this example, the output will be the name of the previous month, which is “January”.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.