Pergunta

I have a Gregorian Date in a String format, I want format it in java.util.Date using SimpleDateFormat I want to do something like that:

String gDate="20-Aug-2012";    
DateFormat sdf= new SimpleDateFormat(dd-MMM-yyyy");        
Date dDate=sdf.parse(gDate);

But this throws java.text.ParseException: Unparseable date: "20-Aug-2013"

Foi útil?

Solução

If using the method format instead of parse was just a typo (you have edited your question this way) and you still get a ParseException then this probably happens because of locale setting. I suggest you to explicitly set the language ("Aug" sounds English, but could also be German, but surely not in Arabic, Russian etc.):

String gDate = "20-Aug-2012";
DateFormat sdf= new SimpleDateFormat(dd-MMM-yyyy", Locale.ENGLISH);
Date dDate = sdf.parse(gDate);

Keep in mind that every text fragment like month names and also abbreviations is sensible to language settings. This is also valid for weekday, timezone and era names. You should never blindly rely on implicit system language setting (Locale.getDefault()).

Outras dicas

Try using the parse() method that takes date String as parameter.

String gDate="20-Aug-2012";
java.text.DateFormat sfd = new java.text.SimpleDateFormat("dd-MMM-yyyy");
Date dDate = sfd.parse(gDate);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top