Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8345756

Calendar.HOUR should get deprecated

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Do you see what is wrong with this code?

      @Test
      public void testEndOfDay() {

      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.DAY_OF_MONTH, 1);
      calendar.set(Calendar.HOUR, 23);
      calendar.set(Calendar.MINUTE, 59);
      calendar.set(Calendar.SECOND, 59);

      assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH));
      assertEquals(23, calendar.get(Calendar.HOUR));
      assertEquals(59, calendar.get(Calendar.MINUTE));
      assertEquals(59, calendar.get(Calendar.SECOND));
      }

      Answer: The call "calendar.get(Calendar.DAY_OF_MONTH)" does return 2 instead of 1 and "calendar.get(Calendar.HOUR)" returns 11 instead of 23. The reason is, that Calendar.HOUR is 12-hour-based instead of 24-hour-based and the set-method just adds the additional hours instead of setting it to a fixed value.

      This behaviour isn't intuitive. When seeing the code, nobody (without knowing the details of the JavaDoc documentation) would expect, that HOUR is 12-based and that set is adding values. I would expect that setting Calendar.HOUR to a value higher than value "11" would throw an Exception. That can't get changed easily because it needs to be downward compatible. But here is a solution which is downward compatible and would prevent developers from mistakes: You could mark Calendar.HOUR as deprecated and introduce a new constant named like Calendar.HOUR_12H. Therefore developers would see that the code is broken and it is easier to read.


            jlu Justin Lu
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: