• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

IllegalArgumentException

 
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written code like this:



When I run this piece of code, I get the following exception.

java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:279)
at java.text.Format.format(Format.java:133)
at Date.formatDate(Date.java:27)
at Date.main(Date.java:37)

Could somebody help me with this please??
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the signatures on DateFormat. There are some that take a String argument like your "2005-02-10" and return a Date object. And Date is just what the format method expects as an argument. So you need a two step process:

String YYYY-MM-DD -> Date -> String MEDIUM
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jayashree,
The following code can solve your problem:-

import java.text.SimpleDateFormat;
import java.text.ParsePosition;

public class dateFormatCode {
public static void main(String[] args){
String date = "2005-02-10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
java.util.Date obj = formatter.parse(date,pos); //Convert to Date
String show = formatter.format(obj);
System.out.println(show);
}
}

If you want to display the entered date text in some other format, you can create it using SimpleDateFormat
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!