Java Convert Date to Start of Day Time

Tags: Java Date DateUtil

In this Java tutorial, we learn how to convert a Date object to another Date object with the same date but the time set to start of the day.

How to convert Date to start of day time in Java

In this first step, we create a new Java class named DateUtil, and implement getStartOfDay(Date date) static method which return the Date with same day, month, year but reset hour, minute, second to zero as the Java code below.

DateUtil.java

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

public class DateUtil {

    /**
     * Populate a new Date object with same date but zero values for hour, minute, second and millisecond
     * @param date the input Date object
     * @return the return Date object with start of day time
     */
    public static Date getStartOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        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 Java program, we show how to use the DateUil class above to convert a Date to another Date with time set to start of the day.

ConvertDateToStartOfDayExample.java

import java.util.Date;

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

        // Convert Date to Start of Day Time
        Date startOfDay = DateUtil.getStartOfDay(date);

        System.out.println("Input: " + date);
        System.out.println("Output: " + startOfDay);
    }
}
The output as below.
Input: Tue Aug 16 17:54:04 ICT 2022
Output: Tue Aug 16 00:00:00 ICT 2022

Happy Coding 😊

Java Convert String to Date

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 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