Calendar.Month gives wrong output

后端 未结 4 1054
滥情空心
滥情空心 2020-11-28 16:09

I have been using java.util for all date and calendar representations. But I am facing a strange problem here. Calendar.MONTH, Calendar.DAY_O

4条回答
  •  北海茫月
    2020-11-28 16:38

    java.time

        ZonedDateTime rightNow = ZonedDateTime.now(ZoneId.of("Africa/Cairo"));
        System.out.println(rightNow.getMonth());
        System.out.println(rightNow.getMonthValue());
        System.out.println(rightNow.getDayOfMonth());
        System.out.println(rightNow.getYear());
        System.out.println(rightNow);
    

    Output when running just now was:

    FEBRUARY
    2
    15
    2019
    2019-02-15T21:15:06.313809+02:00[Africa/Cairo]
    

    Don’t use Calendar

    The Calendar class is confusing and suffers from poor design, so no wonder that you’re wondering. Fortunately it was replaced the year after you asked this quesion by ZonedDateTime and other classes in java.time, the modern Java date and time API. So never use Calendar again now.

    The Calendar class was trying to be very general, so instead of a getMonth method, etc., it had the notion of fields that could be read and set. Since it was designed long before Java had enums, each field had a number and a named constant for that number. So YEAR (of era) was 1, MONTH was 2, etc. To get the value of the field of a Calendar object you were supposed to call the get method passing the appropriate named constant, for example rightNow.get(Calendar.MONTH). Using just rightNow.MONTH is a regularly repeated mistake. It just gives you the value of the constant, 2.

    Link

    Oracle tutorial: Date Time explaining how to use java.time.

提交回复
热议问题