简体   繁体   English

如何从 Java 中的日历 object 构建天、月、年的列表?

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

I want to build a date widget for a form, which has a select list of months, days, years.我想为一个表单构建一个日期小部件,它有一个 select 月、日、年列表。 since the list is different based on the month and year, i cant hard code it to 31 days.由于列表根据月份和年份而有所不同,因此我无法将其硬编码为 31 天。 (eg 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. (例如 2 月有 28 天而不是 30 或 31,有些年份甚至 29 天)我如何使用日历或joda object 为我构建这些列表。

I strongly recommend that you avoid the built-in date and time APIs in Java.强烈建议您避免使用 Java 中的内置日期和时间 API。

Instead, use Joda Time .相反,请使用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.该库类似于(希望)将其纳入 Java 7 的库,并且比内置 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);
    }
}

Here is an example of creating a list of months:以下是创建月份列表的示例:

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

tl;dr tl;博士

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

java.time java.time

The Answer by Jon Skeet is correct but now outdated. Jon Skeet 的答案是正确的,但现在已经过时了。 The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Joda-Time项目现在处于维护模式,团队建议迁移到 java.time 类。

LocalDate

The code in java.time is similar to that of Joda-Time , with a LocalDate class. java.time 中的代码与Joda-Time的代码类似, LocalDate为 class。 The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate class 表示没有时间和时区的仅日期值。

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).您可以询问每个部分、年份编号、月份等。请注意,月份是合理的数字,1-12 月是 1-12(与传统课程不同)。

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 object。

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

YearMonth

To ask for the length of the month , use the YearMonth class.要询问月份的长度,请使用YearMonth class。

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

About java.time关于java.time

The java.time framework is built into Java 8 and later.java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .这些类取代了麻烦的旧日期时间类,例如java.util.Date.Calendarjava.text.SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to java.time. Joda-Time项目现在处于维护模式,建议迁移到 java.time。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。

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… ). java.time 的大部分功能被反向移植到 ThreeTen - Backport 中的Java 6 和 7,并进一步适应Android的使用方法…

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目通过附加类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuarter等等

The Calendar object will tell you the number of days in the current month using getActualMaximum(Calendar.DAY_OF_MONTH) .日历object 将使用getActualMaximum(Calendar.DAY_OF_MONTH)告诉您当前月份的天数。 See an example here .请参阅此处的示例。

From that you can update your lists on each change.从那里您可以在每次更改时更新您的列表。

There are a number of date picker implementations out there for java, which can be used via swing or a web ui. java 有许多日期选择器实现,可以通过 swing 或 web ui 使用。 I would attempt to reuse one of these and avoid writing your own.我会尝试重用其中一个并避免自己编写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Java 中获取年、月和周的列表? - How can I get list of years, months and weeks in Java? Java:如何在不使用日历的情况下操作日期以添加天数或月数? - Java: How can I manipulate date to add days or months without using Calendar? Java - 我如何将日期作为输入并能够添加/减去其天/月/年 - Java - how do I take date as input and be able to add/subtract its days/months/years 如何在两个Calendar对象之间转换确切的时间量(年,月,日,小时,分钟,秒)? - How would I convert the exact amount of time (years, months, days, hours, minutes, seconds) between two Calendar objects? 如何在jsp中显示选定年份(年份)和月份(月份)中的所有日历日期? - How can I display all the calendar dates in jsp, for a selected year in years dropdown and selected month in months dropdown? 如何将时间单位从秒更改为天/月/年 - How to change time unit from seconds to days/months/years 比较Java中的日期 - 只有年,月和日 - Comparing dates in Java - only years, months and days 如何对包含年份的月份列表进行排序 - How to sort a list of months with years 如何在 java 中将月份转换为年份和月份 - How to convert months to years-and-months in java java.sql.Date 可以强制只插入年、月、日到 Oracle 日期列吗 - Can java.sql.Date be forced to insert only years, months, days to an Oracle Date column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM