Java Get First Day of Month from Specified Date

Tags: Java Date DateUtil

In this Java tutorial, we learn how to get the first day of month from a given specified Date object in Java programming language.

How to get first date from month from specified Date

At this first step, we create a new Java class named DateUtil, and implement a new static method named getMonthFirstDate(Date date) to populate the given Date object and return the first day of month as Date of object.

DateUtil.java

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

public class DateUtil {

    /**
     * Get the first Date of month of a given Date object
     * @param date the input Date object
     * @return the first Date of month
     */
    public static Date getMonthFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND));
        calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND));

        return  calendar.getTime();
    }
}

In the following example Java program, we learn how to use the above DateUtil class to get the first day of month from given Date object.

GetMonthFirstDateExample.java

import java.util.Date;

public class GetMonthFirstDateExample {
    public static void main(String... args) {
        Date date = new Date();

        // Get First Day of Month from Specified Date
        Date firstDateOfMonth = DateUtil.getMonthFirstDate(date);

        System.out.println("Input Date: " + date);
        System.out.println("First Date of month: " + firstDateOfMonth);
    }
}
The output as below.
Input Date: Wed Aug 17 13:38:49 ICT 2022
First Date of month: Mon Aug 01 00:00:00 ICT 2022

Happy Coding 😊

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 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 Same Date in Last Month

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