【问题标题】:Seeting the Calendar Object in Java [duplicate]在Java中设置日历对象[重复]
【发布时间】:2013-04-29 00:29:23
【问题描述】:

我在字符串变量中有相应的月份名称,例如 JANUARY 或 FEBRUARY。

现在我如何使用这个字符串变量在 java 中设置日历对象的月份。

我尝试通过 calendar.set 方法进行设置,但它只需要 int 值。

【问题讨论】:

  • @Paul Bellora:非常感谢。

标签: java


【解决方案1】:

您可以使用反射来提取字段的值(请参阅monthValue() 函数)。

public class Main {
    public static void main(String[] args)
            throws NoSuchFieldException, IllegalAccessException {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.MONTH, monthValue("January"));
        System.out.println(c.getTime());
    }

    public static int monthValue(String monthName)
            throws NoSuchFieldException, IllegalAccessException {
        Field monthConstant = Calendar.class.getField(monthName.toUpperCase());
        return monthConstant.getInt(null);
    }
}

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 2014-02-13
    • 2013-02-20
    • 2018-05-30
    • 2011-09-05
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多