3

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Saad Hassan
  • 111
  • 1
  • 5
  • 2
    You may want to consider to stop using `java.util.Calendar` and switch to the `java.time` classes. In any case, the problem is that you should only use the constants for months, or take into account that January is 0, not 1 in `java.util.Calendar`. See the duplicates for more information. – Mark Rotteveel Mar 08 '19 at 21:10
  • I recommend you don’t use `DateFormat`, `SimpleDateFormat` and `Calendar`. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 10 '19 at 11:07
  • It’s this simple: `LocalDate.of(2019, 3, 8).plusWeeks(1)` yields `2019-03-15`. – Ole V.V. Mar 10 '19 at 11:17

1 Answers1

7

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
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292