如何从Java中的日历对象构建日期,月份,年份的列表? [英] How can I build a list of days, months, years from a calendar object in Java?

查看:371
本文介绍了如何从Java中的日历对象构建日期,月份,年份的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为表单构建一个日期窗口小部件,其中包含月,日,年的选择列表。因为列表是不同的基于月和年,我不能硬编码到31天。 (例如,2月有28天不是30或31,有些年甚至29天)
如何使用日历或 joda 对象来构建这些列表。

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中的内置日期和时间API。

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

而是使用 Joda时间。这个库类似于(希望的)使它成为Java 7,并且比内置的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.

现在,

编辑:这里是代码(带有示例):

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);
    }
}

这篇关于如何从Java中的日历对象构建日期,月份,年份的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆