Java Get Same Date in Last Month

Tags: Java Date DateUtil

In this Java tutorial, we learn how to get the Date in previous month with same date and time but different month.

How to get the same Date in last month

At this step, we create a new Java class named DateUtil with a static method named getLastMonthDate() to get the same Date and time but in last month as Java code below.

DateUtil.java

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    /**
     * This method to return the same Date in last month
     * @return the Date
     */
    public static Date getLastMonthDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);

        return calendar.getTime();
    }

}

In the following example Java program, we show how to use the above DateUtil class to get the same Date in last month.

GetLastMonthDateExample.java

import java.util.Date;

public class GetLastMonthDateExample {
    public static void main(String... args) {
        // Get Same Date in Last Month
        Date lastMonthDate = DateUtil.getLastMonthDate();

        System.out.println("Today: " + new Date());
        System.out.println("Last month Date: " + lastMonthDate);
    }
}
The output as below.
Today: Tue Aug 16 21:09:35 ICT 2022
Last month Date: Sat Jul 16 21:09:35 ICT 2022

Happy Coding 😊

Java Convert String to Date

Java Convert Date to Start of Day Time

Java Convert Date to End of Day Time

Java Get First Date of Current Year

Java Get First Date of Current Month

Java Get First Day of Month from Specified Date

Java Get Yesterday Date

Java Get Tomorrow Date

Java Get Last Date of Current Month

Java Get Last Date of Current Year

Java Get Last Date of Specified Month

Java Get Last Date of Specified Year

Java Check if Calendar is Week Day or Weekend Day

Java Check if Date is Week Day or Weekend Day

Java Check if Today is Week Day or Weekend Day

Java Get First Date of Current Week

Java Get Last Date of Current Week

Java Get First LocalDate of Current Week

Java Get Last LocalDate of Current Week

Java Get First LocalDate of Current Month

Java Get Last LocalDate of Current Month

Java Get First LocalDate of Current Year

Java Get Last LocalDate of Current Year