Last active
December 27, 2015 08:59
-
-
Save javagrails/7300405 to your computer and use it in GitHub Desktop.
Operation on java.util.Calendar Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Calendar; | |
public class JavaCalendarAddSubtractDateMonths { | |
public static void main(String[] args) { | |
int monthsToAdd = 2; | |
int monthsToSubtract = 10; | |
Calendar c = Calendar.getInstance(); // this takes current date | |
c.set(Calendar.DAY_OF_MONTH, 1); // set Day as The First day Of The Mont To the Date | |
//System.out.println(c.getTime()); | |
System.out.println("Current date : " + (c.get(Calendar.MONTH) + 1) +"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR)); | |
// add months to current date | |
c.add(Calendar.MONTH, monthsToAdd); | |
String targetedDate = c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH) + 1) +"-"+c.get(Calendar.DATE); | |
System.out.println("targetedDate : " + targetedDate); | |
System.out.println("After Add Moths : " + (c.get(Calendar.MONTH) + 1) +"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR)); | |
c = Calendar.getInstance(); | |
c.add(Calendar.MONTH, -monthsToSubtract); | |
System.out.println("After Subtruct Moths : " + (c.get(Calendar.MONTH) + 1) +"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment