Souciance Eqdam Rashti Souciance Eqdam Rashti - 3 months ago 10
Java Question

Java English date format parsing

My problem is the following. I am reading a file and it contains a bunch of CSV lines. Each line contains some date in the format of

22-mar-2010
or similar i.e. with the format
dd-MMM-yyyy
. I want to convert this to ISO format so it becomes
2010-03-22
.

The code I have looks like this:

private String convertDate(String date) {
DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy", new Locale("en"));
LocalDate parsedDate = LocalDate.parse(date, oldFormat);

DateTimeFormatter newFormat = DateTimeFormatter.ISO_DATE;
String newDate = parsedDate.format(newFormat);
return newDate;
}


The input looks something like this:

sdfdsfslk 28-mar-2007 dfdsljs
sdfdsfslk 20-apr-2014 dfdsljs
sdfdsfslk 13-oct-2005 dfdsljs
sdfdsfslk 20-may-2014 dfdsljs
sdfdsfslk 20-jan-2014 dfdsljs
sdfdsfslk 20-feb-2014 dfdsljs


If include the locale as above or use
withLocale(Locale.ENGLISH)
then it fails at the first row date string. The exception is:

java.time.format.DateTimeParseException: Text '28-mar-2007' could not be parsed at index 3


If I remove the locale part and just have:

DateTimeFormatter.ofPattern("dd-MMM-yyyy");


Then it works until it encounters a date such as
13-oct-2005
. It does not like the English 'oct' and fails at the
LocalDate.parse
row. If I convert oct to okt (Swedish, where I am) then it parses it.

Do I need to change my Locale completely or what is going wrong here? How can I get it to parse dates with months in English even though I am in Sweden?

Answer

I think the problem is that the first letter of the month is lowercase. When you run the same code for 28-Mar-2007 instead of 28-mar-2007 everything works fine.

One quick and dirty solution is:

private String convertDate(String mydate) {

        String date = mydate;
        String firstLetter = date.substring(0,4).toUpperCase();
        String restLetters = date.substring(4).toLowerCase();
        date = firstLetter+restLetters;

        DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy", new Locale("en"));
    LocalDate parsedDate = LocalDate.parse(date, oldFormat);

    DateTimeFormatter newFormat = DateTimeFormatter.ISO_DATE;
    String newDate = parsedDate.format(newFormat);
   return newDate;
  }
Comments