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

前端 未结 5 928
闹比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:35

    tl;dr

    int lengthOfMonth = 
        YearMonth.from( 
                          LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
                      )
                 .lengthOfMonth() ;
    

    java.time

    The Answer by Jon Skeet is correct but now outdated. The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

    LocalDate

    The code in java.time is similar to that of Joda-Time, with a LocalDate class. The LocalDate class represents a date-only value without time-of-day and without time zone.

    A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

    ZoneId z = ZoneId.of( “America/Montreal” );
    LocalDate today = LocalDate.now( z );
    

    You may interrogate for each part, year number, month, etc. Note that months are number sanely, 1-12 for January-December (unlike in the legacy classes).

    int year = today.getYear();
    int monthNumber = today.getMonthValue(); // 1-12 for January-December.
    int dayOfMonth = today.getDayOfMonth();
    

    You can assemble a LocalDate object from those parts.

    LocalDate ld = LocalDate.of( year , monthNumber , dayOfMonth );
    

    YearMonth

    To ask for the length of the month, use the YearMonth class.

    YearMonth ym = YearMonth.from( ld );
    int lengthOfMonth = ym.lengthOfMonth();
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题