Tuesday, August 3, 2010

Get Last Day of Month Date Object in Java

To get a java.util.Date object representing the last day of the month,
we can use the java.util.Calendar class. First, create a Calendar
object and set it's time with a Data object. Next, add one month, set
the day of month to 1, and subtract one day. Finally, create a new
Date object with the Calendar's getTime() method.

import java.text.DateFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

//Java 1.4+ Compatible
// The following example code demonstrates how to get
// a Date object representing the last day of the month
// relative to a given Date object.

public class GetLastDayOfMonth {

    public static void main(String[] args) {

        Date today = new Date();

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DATE, -1);

        Date firstDayOfMonth = calendar.getTime();

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Today            : " + sdf.format(today));
        System.out.println("Last Day of Month: " + sdf.format(firstDayOfMonth));


Here is the output of the example code:
Today            : 2010-08-03
Last Day of Month: 2010-08-31


Pedro said...

Thanks, great stuff!!

Anonymous said...

thank You !!!!

Anonymous said...

thank you!!

Kavita Patil said...

Thank you.