【发布时间】:2013-04-29 00:29:23
【问题描述】:
我在字符串变量中有相应的月份名称,例如 JANUARY 或 FEBRUARY。
现在我如何使用这个字符串变量在 java 中设置日历对象的月份。
我尝试通过 calendar.set 方法进行设置,但它只需要 int 值。
【问题讨论】:
-
@Paul Bellora:非常感谢。
标签: java
我在字符串变量中有相应的月份名称,例如 JANUARY 或 FEBRUARY。
现在我如何使用这个字符串变量在 java 中设置日历对象的月份。
我尝试通过 calendar.set 方法进行设置,但它只需要 int 值。
【问题讨论】:
标签: java
您可以使用反射来提取字段的值(请参阅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);
}
}
【讨论】: