Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate a future date 1

Status
Not open for further replies.

TeamTJ

Programmer
Jul 22, 2003
2
US
I am trying to figure out how to calculate a future date and then format it like I need it.

I need 4 years from today formatted as yyyymmdd.

I tried:
Code:
DateFormat myDate = new SimpleDateFormat("yyyyMMdd");
  Calendar calendar = Calendar.getInstance();

  int year = calendar.get(Calendar.YEAR);
  int month = calendar.get(Calendar.MONTH) + 1;
  int day = calendar.get(Calendar.DAY_OF_MONTH);

  // prints current date:
  System.out.println(year + "" + month + "" + day);

  // add 4 years
  calendar.add(Calendar.DATE, 365 * 4);

  year = calendar.get(Calendar.YEAR);
  month = calendar.get(Calendar.MONTH) + 1;
  day = calendar.get(Calendar.DAY_OF_MONTH);


  System.out.println(year + "" + month + "" + day);


  String strDate = myDate.format((Date)calendar);
but I get Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date

Any suggestions?

Thank you!

Morgan
 
Replace
Code:
String strDate = myDate.format((Date)calendar);
with
Code:
String strDate = myDate.format(calendar.getTime());
and your problem is solved.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top