views:

656

answers:

3

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.

+1  A: 

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);
    }
}
Jon Skeet
Is that relevant? I.e. will that help him build a date widget?
Michael Myers
@mmyers: Absolutely. Once we've fully identified what he's trying to do, if he does it all with Joda Time it will end up being a lot simpler, I believe.
Jon Skeet
@Jon. Very good comment indeed. Not so sure about this as an "answer"
OscarRyz
It'll turn into a proper answer when I've found out the way to get the relevant information from Joda Time. I'm positive it's in here somewhere :)
Jon Skeet
joda-time, the standard answer of all Java date/time questions. In fact, Jon, you could add a simple if(currentQ.tags.contains("java") lockQuestion(currentQ); } to SO's code...
Esko
@Esko: Yup. It should certainly be part of the answer to all questions asking for help using the built-in API, unless it specifically states why Joda Time is not an option. The more work I do with date/time data, the scarier the whole topic becomes - and the more thankful I become for Joda Time.
Jon Skeet
A: 

The Calendar object will tell you the number of days in the current month using getActualMaximum(Calendar.DAY_OF_MONTH). See an example here.

From that you can update your lists on each change.

Michael Brewer-Davis
A: 

There are a number of date picker implementations out there for java, which can be used via swing or a web ui. I would attempt to reuse one of these and avoid writing your own.

emeraldjava