Title is most of the explanation. I'm very simply trying to parse a charSequence/String to a LocalDate. I have two different formats so I make two attempts to parse, but neither are working. Related Code:
public static LocalDate ToDate(CharSequence charSequence ){ // Or String string
LocalDate date = null;
try{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(standardFormat);
// standardDateFormat "dd MMMM, yyyy"
date = LocalDate.parse(charSequence, formatter);
} catch (DateTimeParseException a){
Log.d("ToDate", charSequence + " =/= " + standardFormat + " :: standard format failure");
} finally {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(simpleDateFormat);
// simpleDateFormat = "dd MMM"
date = LocalDate.parse(charSequence, formatter);
} catch (DateTimeParseException a) {
Log.d("ToDate", charSequence + " =/= " + simpleDateFormat + " :: simple format failure");
}
}
return date;
}
The returned exception:
2022-07-19 10:10:14.759 9625-9625/com.learn.myapplication D/ToDate: 19 Jul =/= dd MMMM, yyyy :: standard format failure
2022-07-19 10:10:14.760 9625-9625/com.learn.myapplication D/ToDate: 19 Jul =/= dd MMM :: simple format failure // ?????
That looks like the same format for me so I assume I'm missing some syntax?
Log.d(e.getMessage());. Furthermore, the code within a finally -block will always be executed. However, as your charsequenxe will only be in one of the two formats, the second statement should NOT ALWAYS be executed, but only if the first one is failing!19 Julto aLocalDate, then regardless of the format string you need, you will also need to provide a year value, as well as day and month values.DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("d MMM yyyy").toFormatter(Locale.US);and thenLocalDate ld = LocalDate.parse("19 Jul 2022", formatter);. My dupe-finding is failing me.parse()(from string toLocalDateobject - or whatever you are using) you canformat()from aLocalDateobject (or whatever) to string. Don't write your own datetime class. A vast amount of work and skill has gone into the Javatimepackage. Leverage it! Look around Stack Overflow for plenty of examples. There's an example offormat()in the excellent @basilbourque answer to this question.