Search code examples
javadatejava.util.calendar

How does Calender.set(Calender.Month, ?) Work?


I am writing a method that can advance the date by a given number of weeks. Here is my code:

public class Date {
int year;
int month;
int day;

public Date (int year, int month, int day){
    this.year = year;
    this.month = month;
    this.day = day;

}
    public void addWeeks (int weeks){
    int week = weeks * 7;
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_MONTH, this.day);
    calendar.set(Calendar.MONTH, this.month);
    calendar.set(Calendar.YEAR, this.year);
    calendar.add(Calendar.DAY_OF_MONTH, week);
    System.out.println();
    System.out.println("Date after adding " + weeks + " weeks is: " + dateFormat.format(calendar.getTime()));
}

So if I pass today's date to year, month and day. (03/08/2019) and then call the addWeeks(1) for example, then the date should advance as (03/15/2019) but it gives me (04/15/2019). For some reason the month is always 1 more than what I enter. If I enter 2 for the month, it gives 3, if I enter 3 it gives 4.


Solution

  • Here's why:

    public static final int MONTH: Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

    So, you need:

    calendar.set(Calendar.MONTH, this.month-1);
    
    Jan: 0
    Feb: 1
    Mar: 2
    Apr: 3
    May: 4
    Jun: 5
    Jul: 6
    Aug: 7
    Sep: 8
    Oct: 9
    Nov: 10
    Dec: 11