giladbu giladbu - 17 days ago 5x
Java Question

How can I build a list of days, months, years from a calendar object in Java?

I want to build a date widget for a form, which has a select list of months, days, years. since the list is different based on the month and year, i cant hard code it to 31 days. (e.g february has 28 days not 30 or 31 and some years even 29 days)
How can I use the calendar or joda object to build me these lists.


I strongly recommend that you avoid the built-in date and time APIs in Java.

Instead, use Joda Time. This library is similar to the one which will (hopefully!) make it into Java 7, and is much more pleasant to use than the built-in API.

Now, is the basic problem that you want to know the number of days in a particular month?

EDIT: Here's the code (with a sample):

import org.joda.time.*;
import org.joda.time.chrono.*;

public class Test   
    public static void main(String[] args)
        System.out.println(getDaysInMonth(2009, 2));

    public static int getDaysInMonth(int year, int month)
        // If you want to use a different calendar system (e.g. Coptic)
        // this is the code to change.
        Chronology chrono = ISOChronology.getInstance();
        DateTimeField dayField = chrono.dayOfMonth();        
        LocalDate monthDate = new LocalDate(year, month, 1);
        return dayField.getMaximumValue(monthDate);