Get the Last Day of The Month in Java

Use the getActualMaximum(int field) method of the Calendar class to retrieve the last day of the month.

See the below code for usage details. The code retrieves the last date for Feb 2009 as an example. You can modify the code to accept any valid date.

import java.util.Calendar;

public class GetLastDayOfMonth {
	public static void main(String[] args) {
		// Setup a Calendar instance.
		Calendar cal = Calendar.getInstance();
		cal.setLenient(false);
		// Set the year as 2009
		cal.set(Calendar.YEAR, 2009);
		// Set the month as February (can be set as 1 or Calendar.FEBRUARY)
		cal.set(Calendar.MONTH, 1);
		// Set the date as 1st - optional
		cal.set(Calendar.DATE, 1);
		System.out.println("Input date: " + cal.getTime());
		int lastDateOfMonth = cal.getActualMaximum(Calendar.DATE);
		cal.set(Calendar.DATE, lastDateOfMonth);
		System.out.println("Output Date: " + cal.getTime());
	}
}
Advertisements
This entry was posted in Java and tagged , , . Bookmark the permalink.

One Response to Get the Last Day of The Month in Java

  1. Deepmala says:

    does not work for February.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s