Calendar Month Instance is off by one

2019-09-06 10:01发布

问题:

Here is my code:

Month is passed in on a loop. First 0 (since it is January as I type), then 1, and so on. Next month when it is February, this loop will start from that date. 1, 2, etc.

    int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;

    cal = Calendar.getInstance();
    df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
    cal.set(Calendar.MONTH, month + thisMonth);

    String sMonth = df.format(cal.getTime());

In the first loop, sMonth is March 2015. In the second loop, sMonth is March 2015. In the third loop, sMonth is April 2015. In the fourth loop, sMonth is May 2015. ..and so on

As you see, the first month is NOT February as expected. I believe it is January 29th so that may have some cause as we are so close to February. But if that is the case, why would this happen twice?

I know since I am not working with unix timestamps things aren't exact, is there away to calculate this where I can at least get accurate month ordering?

回答1:

Since today is the 30th, you're getting the current date (2015-01-30), and incrementing the month to get 2015-02-30 - which "rolls over" to 2015-03-02 since February doesn't have 30 days.

One way to avoid this problem is to set the day-of-month to 1 before changing the month.



标签: java calendar