Java Calendar adds a random number of milliseconds?

后端 未结 4 839
栀梦
栀梦 2021-01-21 14:59

Hi I have something weird happening. I am simply taking a calendar object, converting it to its individual parts, and putting it back into a calendar (with or without any change

4条回答
  •  执笔经年
    2021-01-21 15:51

    In the documentation of Calendar.set, it is said :

    Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first.

    The reason is that not all fields are set with this method, in you case, you don't have MILLISECOND set. So it keep the value when the instance was created.

    The call of Calendar.clear will

    Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.

    A quick example :

        Calendar c = GregorianCalendar.getInstance();
        c.clear();
        c.set(2019, Calendar.NOVEMBER, 03, 16, 15, 03);
    
        System.out.println(c.getTime());
        System.out.println(c.getTimeInMillis());
    

    Sun Nov 03 16:15:03 CET 2019
    1572794103000

    Milliseconds being undefined will give 0

提交回复
热议问题