javadatecalendar

Java Calendar returns wrong month


I want store a date into a Calendar Object, like this:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_YEAR, 26);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

All values are set correctly, except the month and if I call cal.getTime() it returns:

Thu Jan 26 10:00:00 CET 2017

What am I doing wrong?


Solution

  • When you use DAY_OF_YEAR you set the number day of the current year.

    DAY_OF_YEAR Field number for get and set indicating the day number within the current year.

    This overrides all sensible configuration like month or year (to current year and month of the number day).


    So instead of use DAY_OF_YEAR you may use DAY_OF_MONTH which seems is what you are looking for, this sets the day of the month you set before.

    DAY_OF_MONTH Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

    So the configuration you are looking for definetively seems it would be like next:

    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.set(Calendar.YEAR, 2017);
    cal.set(Calendar.MONTH, Calendar.JUNE);
    cal.set(Calendar.DAY_OF_MONTH , 26);
    cal.set(Calendar.HOUR_OF_DAY, 9);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    

    Then when you call getTime you will get:

    Mon Jun 26 11:00:00 CEST 2017