adding days to a date

Karen picture Karen · Sep 13, 2009 · Viewed 48.5k times · Source

I have a program that needs to start on 1/1/09 and when I start a new day, my program will show the next day. This is what I have so far:

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy"); 
public void setStart()
{
    startDate.setLenient(false);
    System.out.println(sdf.format(startDate.getTime()));
}

public void today()
{
    newDay = startDate.add(5, 1);
    System.out.println(newDay);
//I want to add a day to the start day and when I start another new day, I want to add another day to that.
}

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

Answer

coobird picture coobird · Sep 13, 2009

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.