PASSWORD RESET

Your destination for complete Tech news

How to get the previous month from a date in React JS?

941 0
< 1 min read

To get the previous month from a given date in React using JavaScript, you can manipulate the Date object. Here’s how you can achieve this:

import React from 'react';

function PreviousMonthDate({ date }) {
  const getPreviousMonthDate = (inputDate) => {
    const currentMonth = inputDate.getMonth();
    const previousMonth = (currentMonth - 1 + 12) % 12; // Get the previous month's index

    const year = inputDate.getFullYear() - (currentMonth === 0 ? 1 : 0); // Decrement year if current month is January
    const day = Math.min(inputDate.getDate(), new Date(year, previousMonth + 1, 0).getDate()); // Handle days at the end of the month

    const previousMonthDate = new Date(year, previousMonth, day);
    return previousMonthDate.toISOString().split('T')[0];
  };

  const previousMonth = getPreviousMonthDate(new Date(date));

  return (
    <div>
      <p>Previous month's date: {previousMonth}</p>
    </div>
  );
}

export default PreviousMonthDate;

In this example, the getPreviousMonthDate function calculates the previous month’s date based on the provided input date. It first gets the current month’s index using getMonth() and calculates the index of the previous month. If the current month’s index is 0 (which is January), it decrements the year. The day is handled to ensure that it doesn’t exceed the last day of the previous month.

The result is formatted as an ISO string, and the date part is extracted using split('T')[0].

You can use this component by passing a date as a prop:

<PreviousMonthDate date="2023-08-15" />

Replace "2023-08-15" with your desired input date in the format “YYYY-MM-DD”. Just as a reminder, JavaScript’s Date object works in the local time zone of the user’s device. If you need to handle time zones or more complex date manipulations, consider using a library like date-fns or moment.js.

Leave A Reply

Your email address will not be published.

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