Java Get Next/Previous Month or Year

1. Java Data Time Format
We should notice that the standard format of the Java Data Time is:
“yyyy-MM-dd HH:mm:ss”
-The signal like “-” can change to “/” to become “yyyy/MM/dd”
-We can use yyyy or yy to display 2 or 4 digits of a year
-MM will display the leading ‘0’ for month as ’03’ for Match. While M will display ‘3’ only
-HH will display the leading ‘0’ for hour as ’04’. While H will display ‘4’ only
-If we need to millisecond, we can use the format “yyyy-MM-dd HH:mm:ss.SSS”. This will display /1000 milisecond. The maximum millisecond can be used is /1000000 as “.SSSSSS”

2.Show the Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
String curDateTime = sdf.format(c.getTime());
System.out.println(“The current data time is ” + curDateTime);

3.Show the Current Date Only
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd”);
String curDate = sdf.format(c.getTime());
System.out.println(“The current data is ” + curDate);

4.Show the Current Time Only
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”);
String curTime = sdf.format(c.getTime());
System.out.println(“The current data is ” + curTime);

5.Show Two Digits for a Year
Calendar c = Calendar.getInstance();
SimpleDateFormat cyf = new SimpleDateFormat(“yy”);
String cyExp = cyf.format(c.getTime());
System.out.println(“The current year 2 digits is: “+cyExp);

6.Show Current Month in 2 Digits
Calendar c = Calendar.getInstance();
SimpleDateFormat cmf = new SimpleDateFormat(“MM”);
//c.add(Calendar.MONTH, 0);
String cmExp = cmf.format(c.getTime());
System.out.println(“The current month: “+cmExp);

7.Get the Next 2 Months
Calendar c = Calendar.getInstance();
SimpleDateFormat cmf = new SimpleDateFormat(“MM”);
c.add(Calendar.MONTH, 2);
String cmExp = cmf.format(c.getTime());
System.out.println(“The next 2 months: “+cmExp);

8.Get the Previous 2 Months
Calendar c = Calendar.getInstance();
SimpleDateFormat cmf = new SimpleDateFormat(“MM”);
c.add(Calendar.MONTH, -2);
String cmExp = cmf.format(c.getTime());
System.out.println(“The previous 2 months: “+cmExp);