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

Wrong GregorianCalendar value changing the day of the week

XMLWordPrintable

      ADDITIONAL SYSTEM INFORMATION :
      Mac OS

      A DESCRIPTION OF THE PROBLEM :
      Using Calendar.set(Calendar.DAY_OF_WEEK, <value>), the resulting value of the variable is wrong, see the code in the example. But if you first READ the value (e.g. calling Calendar.getTimeInMillis method), then the result turns to be OK.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compile and run the code below. The first time, run it as-is, then uncomment the marked line as "UNCOMMENT THIS", and re-run.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      2025-08-11
      ACTUAL -
      2025-08-04

      ---------- BEGIN SOURCE ----------
      import java.text.SimpleDateFormat;
      import java.util.Calendar;
      import java.util.TimeZone;

      public class Sample {

      /*
                    August 2025
              Mon Tue Wed Thu Fri Sat Sun
                                1 2 3
                4 5 6 7 8 9 10
           --> 11 12 13 14 15 (16) 17
               18 19 20 21 22 23 24
               25 26 27 28 29 30 31
      */

      public static void main(String[] args) {
      Calendar dt = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"));
      dt.setFirstDayOfWeek(Calendar.MONDAY);

      // set to 2025-08-16
      dt.set(Calendar.YEAR, 2025);
      dt.set(Calendar.MONTH, Calendar.AUGUST);
      dt.set(Calendar.DATE, 16);

      //dt.getTimeInMillis(); // <-- UNCOMMENT THIS

      dt.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

      // SHOULD BE 2025-08-11
      System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(dt.getTime()));
      }
      }

      ---------- END SOURCE ----------

        1. Sample.java
          0.9 kB
          Patricia Tavares

            pmtavare Patricia Tavares
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: