Java Get Last Date of Specified Year

Tags: Java Date DateUtil

In this Java tutorial, we learn how to implement Java program to get the last day of specified year and return it as a Date object in Java programming language.

How to get last day of specified year in Java

In this first step, we create a new Java class named DateUtil, and implement the static method named getLastDateOfYear(int year) to return the last day of given year as a Date object with the time value set to end of day as the following Java code.

DateUtil.java

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

public class DateUtil {

    /**
     * This method to get the last day of specified year and return as a Date object.
     * @param year the year value
     * @return the last day of year Date object
     */
    public static Date getLastDateOfYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.DAY_OF_YEAR));

        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 example Java code, we learn how to use the the DateUtil class above in Java program to get the last day of given year value and return it as a Date object.

LastDateOfYearExample.java

import java.util.Date;

public class LastDateOfYearExample {
    public static void main(String... args) {
        int year = 2023;

        // Get Last Date of Specified Year
        Date lastDatOfYear = DateUtil.getLastDateOfYear(year);

        System.out.println("Last day of year: " + lastDatOfYear);
    }
}
The output as below.
Last day of year: Sun Dec 31 23:59:59 ICT 2023

Happy Coding 😊

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