为什么会有这样的矛盾呢?
public static void main(String[] args) {
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
System.out.println("KO current month: " + calendar.get(Calendar.MONTH));
calendar.set(Calendar.MONTH, 1);
System.out.println("OK current month: " + calendar.get(Calendar.MONTH));
}
输出:
KO current month: 2
OK current month: 1
发布于 2018-05-31 17:53:37
Karol Dowbecki’s answer是正确的并且解释得很好(我应该说是很好的斑点)。我想提供好的和现代的修复方法。
LocalDate date = LocalDate.of(2018, Month.MAY, 31);
date = date.with(Month.FEBRUARY);
System.out.println(date.getMonth());
System.out.println(date);
输出:
FEBRUARY
2018-02-28
Calendar
类令人困惑且设计糟糕,所以我使用的是java.time
的LocalDate
,它是现代的Java date and time API。这个API使用起来要好得多。幸运的是,LocalDate
不会给你2月31日,因为这个日期不存在。它给出了二月的最后一天,也就是你所期望的月份。
PS以下初始化将模仿您的代码:
LocalDate date = LocalDate.now(ZoneId.of("Europe/Paris"))`
然而,我更喜欢给出代码,当有人在未来某一天试图运行它时,代码也会演示这一点。
链接: Oracle tutorial: Date Time解释如何使用java.time
。
https://stackoverflow.com/questions/50621049
复制相似问题