I am trying to compare these two dates :
17 Oct. 2019 (08:23)
19 déc. 2019 (21:15)
The months are in French and the main problem is the months. Do I need to put an if statement for every type of month so I can switch it with the appropriate month? For example:
if (MonthValue.equals("oct."){
DateValue.replace("oct.","10");
}
Or is there an easier solution, because I need to check in a table if the first value is bigger than the second one.
Edit : My new Code :
String target1 = "17 oct. 2019 (08:23)";
String target2 = "19 déc. 2019 (21:15)";
DateFormat df = new SimpleDateFormat("dd MMM. YYYY (kk:mm)", Locale.FRENCH);
Date result = df.parse(target1);
Date result2 = df.parse(target2);
System.out.println(result);
System.out.println(result2);
if(result.compareTo(result2) < 0) {
System.out.println("true");
}
else {
System.out.println("false");
}
Doesn't work gives this error:
java.text.ParseException: Unparseable date: "17 oct. 2019 (08:23)"
java.time and optional parts in the format pattern string
Like the others I recommend that you use java.time, the modern Java date and time API, for your date and time work. I understand that if your month names are five letters or shorter (for example avril), they are written out in full, whereas if they are seven letters or longer (for example juillet), they are abbreviated. The following formatter can parse in both situations:
Square brackets
[]in the format pattern string surround optional parts.MMMMis for full month name.MMMis for the abbreviation. So the point in[MMMM][MMM]is that it will successfully parse either full month name or abbreviations and just skip the one that doesn’t work. Since you gave an example ofOct.being written with an upper caseO, I have also specified that the parsing should not be sensitive to case. If this is not necessary, you may use this simpler formatter:In order to check that all months work, I have set up these test data:
To parse and compare two of them use
LocalDateTime.parse()and.isBefore():Output:
For comparison you may also exploit the fact that
LocalDateTimeimplementsComparable. This is practical when sorting the dates and times, for example. As a brief example let’s sort all theLocalDateTimeobjects that come out of parsing the above strings:Link: Trail: Date Time (The Java™ Tutorials) explaining how to use java.time.