Calendar add method error when going beyond the ye

2019-09-27 15:55发布

问题:

I must be using the java.util.Calendar#add(...) method wrong as it is giving me unexpected results. Assume some initial conditions:

  • I create a Calendar object and initialize it to January 30, 2012.
  • I try to add 47 weeks to it, extract the Date from it and print out the results.
  • I try to add 48 weeks to the original instance (or a cloned copy of it), and print out the results.

I would assume that there would be 7 days difference between the two results, but I'm getting 7 days + 1 year.

For example:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

public class CalendarFun {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();

      cal.set(Calendar.MONTH, Calendar.JANUARY);
      cal.set(Calendar.DAY_OF_MONTH, 30);
      cal.set(Calendar.YEAR, 2012);

      Date date = cal.getTime();
      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY");
      System.out.println(dateFormat .format(date));

      Calendar newCal = (Calendar) cal.clone();
      newCal.add(Calendar.WEEK_OF_YEAR, 47);
      System.out.println("add 47 weeks: " + dateFormat.format(newCal.getTime()));

      newCal = (Calendar) cal.clone();
      newCal.add(Calendar.WEEK_OF_YEAR, 48);
      System.out.println("add 48 weeks: " + dateFormat.format(newCal.getTime()));
   }
}

This prints out:

01/30/2012
add 47 weeks: 12/24/2012
add 48 weeks: 12/31/2013

12/31/2013? What am I doing wrong?

回答1:

Your code didn't compile for me unless I changed the YYYY to yyyy. After that it seems to work fine.