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

前端 未结 5 883
闹比i
闹比i 2021-01-06 14:46

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

5条回答
  •  耶瑟儿~
    2021-01-06 15:30

    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);
        }
    }
    

提交回复
热议问题