java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.util arrow Add/Substract Day/Month/Year to a Date
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 3940
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Add/Substract Day/Month/Year to a Date E-mail
User Rating: / 76
PoorBest 

add() and roll() are used to add or substract values to a Calendar object.

You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

add() adds or substracts values to the specified Calendar field, the next larger field is modified when the result makes the Calendar "rolls over".

String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = 
      new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance()
c1.set(199920)// 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.DATE,20);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));

To substract, simply use a negative argument.

roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result.

String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = 
      new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance()
// roll down the month
c1.set(199920)// 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.roll(Calendar.MONTH, false)// roll down, substract 1 month
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()))// 1999 jan 20

c1.set(199920)// 1999 jan 20 
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1)// substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()))// 1998 dec 20

 Related Tips

 
Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.