In this article we will see how to get previous month date using java.

By using the classes such as LocalDate & TemporalAdjusters inside the time package, we can easily get the date of the previous month.

Let’s first import the necessary packages & create an instance of LocalDate class representing the current date using the LocalDate.now() method.

By using the Temporal.adjusters we get the first day of current month.

Next, we use the minusMonths() method to subtract one month from the first day of the current month, which gives us the last day of the previous month which we want to retreive.

Finally, we print out the previous month’s date to the console using the System.out.println() method.

Example

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class PreviousMonthDateExample {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        LocalDate previousMonthDate = currentDate.with(TemporalAdjusters.firstDayOfMonth())
                .minusMonths(1);
        System.out.println("Previous month's date: " + previousMonthDate);
    }
}

Output

Previous month's date: 2023-03-31

We can also customize the date format using the DateTimeFormatter class to print the date in a specific format.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class PreviousMonthDateExample {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        LocalDate previousMonthDate = currentDate.with(TemporalAdjusters.firstDayOfMonth())
                .minusMonths(1);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        System.out.println("Previous month's date: " + previousMonthDate.format(formatter));
    }
}

In the above example, we created an instance of the DateTimeFormatter class and use it to format the previous month’s date in the “dd/MM/yyyy” format. We then print out the formatted date to the console.

Categorized in:

Tagged in: