I want to increment months by 6 in Java, currently I am using below code. But it is always printing first month. Can you kindly let me know what I am doing mistake here? I am beginner in Java.
This is my output :
Current date : 11-1-2013
date after 6 months : 11-7-2013
Expected output:
Current date: 11-05-2013
date after 6 months : 11-11-2013
String dt = "11-05-2013";
DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
Date date = null;
try {
date = (Date)formatter.parse(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
now.setTime(date);
System.out.println("Current date : " + now.get(Calendar.DATE)+ "-" +(now.get(Calendar.MONTH) + 1) + "-"
+ now.get(Calendar.YEAR));
now.add(Calendar.MONTH, 6);
System.out.println("date after 6 months : " + now.get(Calendar.DATE)+"-" + (now.get(Calendar.MONTH) + 1) + "-"
+ now.get(Calendar.YEAR));
Try with capital M:
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With