adding days to a date

纵饮孤独 提交于 2019-11-30 18:50:30

The Calendar object has an add method which allows one to add or subtract values of a specified field.

For example,

Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

The constants for specifying the field can be found in the "Field Summary" of the Calendar class.

Just for future reference, The Java API Specification contains a lot of helpful information about how to use the classes which are part of the Java API.


Update:

I am getting the error found void but expected int, in 'newDay = startDate.add(5, 1);' What should I do?

The add method does not return anything, therefore, trying to assign the result of calling Calendar.add is not valid.

The compiler error indicates that one is trying to assign a void to a variable with the type of int. This is not valid, as one cannot assign "nothing" to an int variable.

Just a guess, but perhaps this may be what is trying to be achieved:

// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);

// Get the current date representation of the calendar.
Date startDate = calendar.getTime();

// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);

// Get the current date representation of the calendar.
Date endDate = calendar.getTime();

System.out.println(startDate);
System.out.println(endDate);

Output:

Thu Jan 01 00:00:00 PST 2009
Fri Jan 02 00:00:00 PST 2009

What needs to be considered is what Calendar actually is.

A Calendar is not a representation of a date. It is a representation of a calendar, and where it is currently pointing at. In order to get a representation of where the calendar is pointing at at the moment, one should obtain a Date from the Calendar using the getTime method.

If you can swing it requirement wise, move all your date/time needs to JODA, which is a much better library, with the added bonus that almost everything is immutable, meaning multithreading comes in for free.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!