0

I want to try parse so simple date on Java-11.

Date language is: Hebrew Date format is: "MMM YYYY dd" Example date is: "18 אוק 2010"

And my code looks like:

DateTimeFormatter f = DateTimeFormat.forPattern("MMM YYYY dd")
                                    .withLocale(Locale.forLanguageTag("iw-IL"));
String dateInString = "18 אוק 2010";
Date d = f.parseDateTime(dateInString).toDate();
System.out.println(d);

But when I try it, I get an error like:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "18 אוק 2010" is malformed at "אוק 2010"
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)

Is there any suggestion?

Sha
  • 921
  • 17
  • 46
  • Use the same format string to print the date in question, then see where that output differs from what you're trying to parse. – Andreas Jan 08 '21 at 14:51
  • 1
    @Andreas Usually a nery good tip. I tried. In this particular case I couldn’t immediately tell the difference (there was one, though; see my answer). – Ole V.V. Jan 08 '21 at 21:03

1 Answers1

2

Reading direction

Your format pattern string , MMM YYYY dd, says that the month abbreviation comes first, then year, then day of month. It’s impossible to tell from the look, but when I copy-paste your date string, 18 אוק 2010, then day of month (18) comes first, then the month abbreviation (אוק for October) and then finally the year (2010). Since Hebrew is read right to left and the rest left to right, the string looks the same in both cases. And since the order really does not agree behind the scenes, parsing fails.

So the solutions are two (at least):

  1. Fix your date string to match the format pattern.

  2. Fix your format pattern to match the date string:

    DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM YYYY")
            .withLocale(Locale.forLanguageTag("iw-IL"));
    

In the latter case output from your code is (in my time zone):

Mon Oct 18 00:00:00 CEST 2010

It doesn’t work readily on all Java versions

… but this doesnt work on java-11. But it works on java-8

That’s because the default locale data have changed in Java 9. Until Java 8 Java’s own locale data were used as the default. From Java 9 CLDR (Unicode Common Locale Date Repository) is the default. Here the Hebrew abbreviation for October is אוק׳. For how to make parsing of the string you have got work on Java 9, 11 and later, see JDK dateformatter parsing DayOfWeek in German locale, java8 vs java9.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Ole thanks for your answer but this doesnt work on java-11. But it works on java-8 – Sha Jan 09 '21 at 08:27
  • Thanks Ole, the problem is related with abbreviation like you said. Could you please add your comment to your answer maybe others can see it easily? – Sha Jan 11 '21 at 07:16