Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javadate Rolling Time Span in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Rolling Time Span in Java

Advertisement
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.

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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 14, 2008

Related Tutorials

Discuss: Rolling Time Span in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com