Get Last Day Of The Month From Date Object
In this example we show you how you can get the last day of the month. Most of the time we use a java.util.Date
Object to represent a Date. We can use the java.util.Calendar
class to manipulate the date object. First we create a Calendar Object and set it’s time with a Date Object. Next we can set the Day of the Month to the ‘actual maximum’. The Calendar class knows in which month there are how many days. Finally we return a new Date Object representing the Last day of the Month.
Last Day Of The Month
package com.memorynotfound.date;
import java.util.Calendar;
import java.util.Date;
public class GetLastDayOfMonth {
public static void main(String... args){
System.out.println("Last day of the month: " + getLastDateOfMonth(new Date()));
}
public static Date getLastDateOfMonth(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
}
Demo
Last day of month: Sat Jan 31 14:21:32 CET 2015
How can I do the same without Day and time, just return January 31, 2015?
Last day of month: Sat Jan 31 14:21:32 CET 2015