-1

Hi I need to convert string to date below is my code,

String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println("Date././."+date);

If i run my code am getting parse exception as like below,

java.text.ParseException: Unparseable date: "January 2,2010"

Mureinik
  • 252,575
  • 45
  • 248
  • 283
Suganth.MKR
  • 35
  • 1
  • 6
  • 1
    Well yes - look at the format of your actual value, and look at the pattern you're specifying. They're nothing like each other. Please read the documentation for `SimpleDateFormat`. – Jon Skeet May 21 '16 at 07:32
  • actually am getting this input string is from another file in the above mentioned format and the output also i need to be in this format(MM/dd/yyyy) so only i mentioned like this – Suganth.MKR May 21 '16 at 07:35
  • Right, but you're not using that code to *format* - you're using it to *parse*. So parse with the pattern matching the input data, then format with another pattern. Read https://codeblog.jonskeet.uk/2015/05/05/common-mistakes-in-datetime-formatting-and-parsing/ – Jon Skeet May 21 '16 at 07:36

1 Answers1

2

Your format needs to match the date you're trying to parse. E.g., for your usecase:

String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMMM dd, yyyy", Locale.ENGLISH);
Mureinik
  • 252,575
  • 45
  • 248
  • 283