简体   繁体   中英

Java Calendar class add method adds zero on first call?

When adding 1 year to a Calendar object the first iteration adds zero years, even though it should add 1. Each subsequent call adds 1 year, as it should. For example:

calendarObject.add(Calendar.YEAR,1); //This actually adds nothing    
calendarObject.add(Calendar.YEAR,1); // now it works.

Note: calendarObject has been set to have a year of 1995 with no other properties set.

It just works fine.

import java.util.Calendar;


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

        cal.set(Calendar.YEAR, 1995);
        System.out.println(cal.get(Calendar.YEAR));

        cal.add(Calendar.YEAR, 1);
        System.out.println(cal.get(Calendar.YEAR));

        cal.add(Calendar.YEAR, 1);
        System.out.println(cal.get(Calendar.YEAR));
    }
}

output:

1995
1996
1997

The Note is the source of the problem. You need to have more of the Calendar properties set other than just year. Vikdor's example works because he is using the default Calendar instance returned, which has all class members filled out. Just specifying "1995" will cause odd behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM