Java Convert Date to End of Day Time

Tags: Java Date DateUtil

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

How to convert Date to end of day time in Java

In this first step, we create a new Java class named DateUtil, and implement a new static method named getEndOfDay(Date date) to convert a Date object to another Date with the same day, month, year but set the hour, minute, second to end of the day.

DateUtil.java

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

public class DateUtil {

    /**
     * Convert a Date object to a new Date with time at end of the day
     * @param date the input Date object
     * @return the return Date object with time at end of the day
     */
    public static Date getEndOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
        calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND));

        return calendar.getTime();
    }
}

In the following Java program, we show how to use the DateUtil class above to convert a Date object to another Date object with the time set to end of the day.

ConvertDateToEndOfDayExample.java

import java.util.Date;

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

        // Convert Date to End of Day Time
        Date startOfDay = DateUtil.getEndOfDay(date);

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

Happy Coding 😊

Java Convert String to Date

Java Convert Date to Start 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