GregorianCalendar的奇怪行为 [英] Strange behaviour with GregorianCalendar
问题描述
我在GregorianCalendar类中遇到了一个奇怪的行为,我想知道我是否真的做得不好。
I just encountered a strange behaviour with the GregorianCalendar class, and I was wondering if I really was doing something bad.
这仅在初始化日期的月份为实际的最大值大于我要设置日历的月份。
This only appends when the initialization date's month has an actualMaximum bigger than the month I'm going to set the calendar to.
下面是示例代码:
// today is 2010/05/31
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, 1); // FEBRUARY
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
return cal.getTime(); // => 2010/03/03, wtf
我知道问题是由日历初始化日期引起的是31天(五月),与设置为2月(28天)的月份相混淆。修复很容易(只需在设置年和月之前将day_of_month设置为1),但是我想知道这确实是想要的行为。有什么想法吗?
I know the problem is caused by the fact that the calendar initialization date is a 31 day month ( may ), which mess with the month set to february (28 days). The fix is easy ( just set day_of_month to 1 before setting year and month ), but I was wondering is this really was the wanted behaviour. Any thoughts ?
推荐答案
它正在获取当前日期/时间的实际最大值。 5月有31天,比2月28日晚3天,因此将转移到3月3日。
It is getting the actual maximums of the current date/time. May has 31 days which is 3 more than 28 February and it will thus shift to 3 March.
您需要致电 Calendar#clear()
在获得/创建后:
You need to call Calendar#clear()
after obtaining/creating it:
GregorianCalendar cal = new GregorianCalendar();
cal.clear();
// ...
结果为:
Sun Feb 28 23:59:59 GMT-04:00 2010
(根据我的时区是正确的)
(which is correct as per my timezone)
正如答案之一所说, java。 util.Calendar
和 Date
是史诗般的失败。在进行密集的日期/时间操作时,请考虑 JodaTime 。
As said in one of the answers, the java.util.Calendar
and Date
are epic failures. Consider JodaTime when doing intensive date/time operations.
这篇关于GregorianCalendar的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!