Search code examples
javadatesimpledateformatstring-parsing

Problems converting strings to dates


I exctract dates from a big document via regex and want to save them into Java dates. This works for most of the dates, but not for dates in December.
I think it has something to do with the way it is written, because when I change its spelling from "Dec" to "Dez", they can be converted.

SimpleDateFormat dateFormat01 = new SimpleDateFormat("HH:mm, dd MMM yyyy (zzz)");

String s01 = "20:49, 13 Jan 2005 (UTC)"; //working
String s02 = "20:49, 13 Dez 2005 (UTC)"; //working
String s03 = "20:49, 13 Dec 2005 (UTC)"; //not working

Date d01 = dateFormat01.parse(s01);
Date d02 = dateFormat01.parse(s02);
Date d03 = dateFormat01.parse(s03);

Solution

  • As you can see, the parsing is working sometimes

    String s01 = "20:49, 13 Jan 2005 (UTC)"; //working
    String s02 = "20:49, 13 Dez 2005 (UTC)"; //working
    String s03 = "20:49, 13 Dec 2005 (UTC)"; //not working
    

    the reason is quite simple, you NEED to use Locale in the SimpleDateFormat, otherwise java will never understand if "20:49, 13 Dec 2005 (UTC)" is December (English language) or Dezember (german language)

    ... new SimpleDateFormat("HH:mm, dd MMM yyyy (zzz)", Locale.EN);
    

    when I see where is the code working or not, I can infer, your java is running on a german Localized env. therefore 13 Jan 2005 can be :

    13 January 2005 (English Locale) or 13 Januar 2005 (German Locale), both cases coincidentially begin with the same char sequence....

    not the case for December/Dezember