Strange behaviour with GregorianCalendar

后端 未结 8 1810
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 22:34

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 initiali

8条回答
  •  星月不相逢
    2021-01-01 23:13

    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.

    You need to call Calendar#clear() after obtaining/creating it:

    GregorianCalendar cal = new GregorianCalendar();
    cal.clear();
    // ...
    

    This results in:

    Sun Feb 28 23:59:59 GMT-04:00 2010
    

    (which is correct as per my timezone)

    As said in one of the answers, the java.util.Calendar and Date are epic failures. Consider JodaTime when doing intensive date/time operations.

提交回复
热议问题