Tuesday, August 3, 2010

Get First Day of Month Date Object in Java

To get a java.util.Date object representing the first 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, set the
Calendar's 'day of month' to 1. Finally, create a new Date object with
the Calendar's getTime() method.


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 first day of the month
// relative to a given Date object.

public class GetFirstDayOfMonth {

    public static void main(String[] args) {

        Date today = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);

        calendar.set(Calendar.DAY_OF_MONTH, 1);

        Date firstDayOfMonth = calendar.getTime();

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

Here is the output of the example code:
Today             : 2010-08-03
First Day of Month: 2010-08-01

2 comments:

Juan Pablo Angamarca said...

Great tip dude, thanks.

hoangminh218 said...

Doesn't this do the same thing?

Calendar c = Calendar.getInstance();
c.set(c.DATE, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("First day of the month: " + sdf.format(c.getTime()));