Tuesday, May 25, 2010

Determine the Next Month in Java

First, get an instance of the Calendar class:

Calendar cal = GregorianCalendar.getInstance();
Declare a format to be used:
SimpleDateFormat df = new SimpleDateFormat("MMM yyyy");

Set the Calendar's current time to today's Date:

cal.setTime(new Date());

Add a month to the Calendar's date:

cal.add(Calendar.MONTH, 1);

Format the new date into a string:

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

The nextMonth String will contain the next month's value.

The following technique allows us to show 12 consecutive months:

cal.setTime(new Date());
for(int i=0; i<12;i++){
   cal.add(Calendar.MONTH, 1);
   String nextMonth = df.format(cal.getTime());
   System.out.println(nextMonth);
}


The Calendar class has a lot of other methods to set its date. For example, you can set the year and month as follows:

cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, 05);
or
cal.set(Calendar.MONTH, Calendar.JUNE);

This code sets the Calendar date to June 2010.

You can also set the date using year, month, and day arguments.

cal.set(2010, 05, 15);

This code sets the Calendar date to June 15, 2010.

No comments:

Post a Comment