問題描述
我想為一個表單構(gòu)建一個日期小部件,它有一個包含月、日、年的選擇列表.由于列表根據(jù)月份和年份而有所不同,因此我無法將其硬編碼為 31 天.(例如 2 月有 28 天而不是 30 或 31 天,有些年份甚至是 29 天)如何使用日歷或 joda 對象為我構(gòu)建這些列表.
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 days. (e.g 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.
推薦答案
我強烈建議您避免使用 Java 中內(nèi)置的日期和時間 API.
I strongly recommend that you avoid the built-in date and time APIs in Java.
改為使用 Joda Time.這個庫類似于(希望如此!)進(jìn)入 Java 7 的庫,并且比內(nèi)置 API 更易于使用.
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.
現(xiàn)在,您想知道特定月份的天數(shù)是基本問題嗎?
Now, is the basic problem that you want to know the number of days in a particular month?
這是代碼(帶有示例):
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);
}
}
這篇關(guān)于如何從 Java 中的日歷對象構(gòu)建天、月、年的列表?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!