1

I want to convert this string to the following date format.

  String s = "2-26-2013";
  Date date = new SimpleDateFormat("EEEE, MMMM/dd/yyyy").parse(s);
  System.out.println(date);

I'm getting this error:

Exception in thread "main" java.text.ParseException: Unparseable date: "2-26-2013"
    at java.text.DateFormat.parse(DateFormat.java:357)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Muhsina M
  • 21
  • 2
  • 8

3 Answers3

4

Well yes. The argument you pass into the constructor of SimpleDateFormat says the format you expect the date to be in.

"EEEE, MMMM/dd/yyyy" would be valid for input like "Tuesday, February/26/2013". It's not even slightly valid for "2-26-2013". You do understand that you're parsing the text at the moment, not formatting it?

It looks like you want a format string of "M-dd-yyyy" or possibly "M-d-yyyy".

If you're trying to convert from one format to another, you need to first specify the format to parse, and then specify the format to format with:

SimpleDateFormat parser = new SimpleDateFormat("M-dd-yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM/dd/yyyy");
Date date = parser.parse(input);
String output = formatter.format(date);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • any suggestions, i just want to convert the string in a suitable format so that i can retrieve them by year. – Muhsina M Feb 26 '13 at 09:47
  • what do you mean "retrieve them by year"? DO you mean extract the year part of the date? – NickJ Feb 26 '13 at 09:50
  • @MuhsinaM: What do you mean by "retrieve them by year"? What does that have to do with formatting as text? – Jon Skeet Feb 26 '13 at 09:50
  • actually when i'm converting them to date, i'm storing it in a database and later another method is retrieving every record based on specific year/date – Muhsina M Feb 26 '13 at 09:53
0
Date date = new SimpleDateFormat("MM-dd-yyyy").parse(s);

The argument to SimpleDateFormat defines the format your date it in. The above line matches your format, and works. Your example does not match.

NickJ
  • 9,380
  • 9
  • 51
  • 74
0

Instead of using MMMM/dd/yyyy you need to used MM-dd-yyyy. SimpleDateFormat expects the pattern to match what its trying to parse.

Aashray
  • 2,753
  • 16
  • 22