我想为一个表单构建一个日期小部件,它有一个包含月、日、年的选择列表。由于列表根据月份和年份而有所不同,因此我无法将其硬编码为 31 天。(例如,二月有 28 天而不是 30 或 31,有些年份甚至 29 天)我如何使用日历或joda对象来构建这些列表。
问问题
6120 次
5 回答
3
我强烈建议您避免使用 Java 中的内置日期和时间 API。
相反,请使用Joda Time。这个库类似于将(希望!)进入 Java 7 的库,并且比内置 API 更易于使用。
现在,您想知道特定月份的天数是基本问题吗?
编辑:这是代码(带有示例):
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);
}
}
于 2009-03-20T21:39:41.273 回答
0
有许多用于 java 的日期选择器实现,可以通过 swing 或 web ui 使用。我会尝试重用其中一个并避免自己编写。
于 2009-03-21T08:13:17.770 回答
0
以下是创建月份列表的示例:
String[] months = new DateFormatSymbols().getMonths();
List<String> allMonths = new ArrayList<String>();
for(String singleMonth: months){
allMonths.add(singleMonth);
}
System.out.println(allMonths);
于 2016-10-06T19:53:55.870 回答
0
于 2016-10-06T21:15:13.893 回答