Rolling Time Span in Java

In the previous example of adding and subtracting time span we have added and subtracted the time spans accordingly and since add() method automatically do the rolling according to the calendar.

Rolling Time Span in Java

In the previous example of adding and subtracting time span we have added and subtracted the time spans accordingly and since add() method automatically do the rolling according to the calendar.

Rolling Time Span in Java

Rolling Time Span in Java

     

In the previous example of adding and subtracting time span we have added and subtracted the time spans accordingly and since add() method automatically do the rolling according to the calendar.

We can roll up the current date by one day as calendar.roll(Calendar.DATE,true);

For rolling current month up by one we can write code as calendar.roll(Calendar.MONTH,true);

We can also roll year up by one year as calendar.roll(Calendar.YEAR,true); Here the second parameter's Boolean value true means rolling in upward direction and false means downwards.

Here is the full example code of RollingTimeSpan.java as follows:

RollingTimeSpan.java

 import java.text.*;
 import java.util.Calendar;
 import java.util.GregorianCalendar; 

 public class RollingTimeSpan
 {
 public static void main(String[] args)
 {
  // set calendar to 10 DECEMBER 2008
 Calendar calendar = new GregorianCalendar(2008,Calendar.DECEMBER,10);
 System.out.println("Before Rolling date is: ");
 SimpleDateFormat formatter = new SimpleDateFormat("d-MMMM-yyyy hh:mm");
 System.out.println(formatter.format(calendar.getTime()));
 
 System.out.println("-------------- Rolling -----------------");
 // Rolling Date 
  calendar.roll(Calendar.DATE,true)
 // Rolling Month 
  calendar.roll(Calendar.MONTH,true);
 // Rolling Year 
  calendar.roll(Calendar.YEAR,true);  
 
 System.out.println("After Rolling 1 day 1 Month and 1 Year date is: ");
 formatter = new SimpleDateFormat("d-MMMM-yyyy hh:mm");
 System.out.println(formatter.format(calendar.getTime()));
 }  
 }

Output:

C:\DateExample>javac RollingTimeSpan.java

C:\DateExample>java RollingTimeSpan
Before Rolling date is:
10-December-2008 12:00
-------------- Rolling -----------------
After Rolling 1 day 1 Month and 1 Year date is:
11-January-2009 12:00

Download Source Code