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

I want to create a date widget for a form that has a selected list of months, days, years. since the list is different from month and year, I can’t write it down to 31 days. (for example, February has 28 days, not 30 or 31, but several years, even 29 days) How to use a calendar or joda to create these lists.

+3
source share
5 answers

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

Use Joda Time instead . This library is similar to the one that (hopefully!) Will turn into Java 7 and will be much more pleasant to use than the built-in API.

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

EDIT: here is the code (with 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);
    }
}
+3
source

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

From this, you can update your lists with every change.

0
source

java, swing web ui. .

0

:

String[] months = new DateFormatSymbols().getMonths();
    List<String> allMonths = new ArrayList<String>();
    for(String singleMonth: months){
        allMonths.add(singleMonth);
    }
    System.out.println(allMonths);
0

TL;DR

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

java.time

Jon Skeet , . Joda-Time , java.time.

LocalDate

java.time Joda-Time LocalDate. LocalDate .

. . , - , "" .

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

, , .. , , 1-12 - ( ).

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

LocalDate .

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

YearMonth

, YearMonth.

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

java.time

java.time Java 8 . , java.util.Date, .Calendar java.text.SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru .

java.time Java 6 7 ThreeTen-Backport Android ThreeTenABP (. ...).

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .

0

Source: https://habr.com/ru/post/1705117/


All Articles