Pergunta

I need to parse a string to date. But getting an unparseable exception. Following is my code:

String str="Sat Oct 12 09:05:00 IST 2013";
SimpleDateFormat format = new SimpleDateFormat("EEE MM DD hh:mm:ss yyyy");
try {
   format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
Foi útil?

Solução

Your format has several issues:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
  • D denotes day in year, not day in month
  • You're missing the time zone
  • The format for month is incorrect
  • Since you're time is in 24-hour format, you need H instead of h

Refer to SimpleDateFormat documentation for information on Date and Time Patterns.

Outras dicas

Your format for parsing that string is wrong. You need to use this format.

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); // Default Locale
  • MMM - is the proper month format in your case
  • z - you missed the pattern for timezone
  • d - represents the day in the month not D which represents day in the year.
  • And as suggested, you might want to use H instead of h as the hour seems to be in the 24-hour format.

Have a look at the docs to learn more about the Date and Time Patterns.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top