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.
views:
656answers:
3
+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
2009-03-20 21:39:41
Is that relevant? I.e. will that help him build a date widget?
Michael Myers
2009-03-20 21:40:25
@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
2009-03-20 21:43:22
@Jon. Very good comment indeed. Not so sure about this as an "answer"
OscarRyz
2009-03-20 21:46:15
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
2009-03-20 21:47:55
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
2009-03-20 21:58:18
@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
2009-03-20 22:05:54
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
2009-03-20 21:42:01
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
2009-03-21 08:13:17