0

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?

8
  • 2
    I think it would be helpful to know the Error message of the DateTimeParseException instead of only the message which you created yourself. Could you please add the following to the catch-blocks and show the log output: 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! Commented Jul 19, 2022 at 17:33
  • 1
    If you're trying to parse 19 Jul to a LocalDate, then regardless of the format string you need, you will also need to provide a year value, as well as day and month values. Commented Jul 19, 2022 at 17:58
  • With a year provided: DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("d MMM yyyy").toFormatter(Locale.US); and then LocalDate ld = LocalDate.parse("19 Jul 2022", formatter);. My dupe-finding is failing me. Commented Jul 19, 2022 at 18:16
  • Awesome help guys. Haven't tested it yet, but I assume it will work, as my other circumstances work where the year is included. A quick question though, is LocalDateTime serializable? I'm considering implementing my own DateTime so that I can easily serialize it but would prefer to just use the existing DateTime. Commented Jul 19, 2022 at 21:01
  • Instead of parse() (from string to LocalDate object - or whatever you are using) you can format() from a LocalDate object (or whatever) to string. Don't write your own datetime class. A vast amount of work and skill has gone into the Java time package. Leverage it! Look around Stack Overflow for plenty of examples. There's an example of format() in the excellent @basilbourque answer to this question. Commented Jul 19, 2022 at 21:39

1 Answer 1

2

Firstly, educate the publisher of your data about using only standard ISO 8601 formats when exchanging date-time values textually. The localized text seen in your code should be used only for presentation to the user, not for data exchange nor data storage.

Standard format for a date is YYYY-MM-DD. For a month with day, --MM-DD.

For a month and day-of-month value, use MonthDay. Without a Year, you cannot put such a value in a date type.

If you insist on parsing localized strings, provide a Locale by which to determine a human language and cultural norms to parse items such as month name.

Do not override the exceptions with your own messages. Because of doing so we cannot properly diagnose your issues.

Generating localized text.

Locale locale = Locale.US ;
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
MonthDay md = MonthDay.now( z ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd MMM" ).withLocale( locale ) ;
String output = md.format( f) ;
System.out.println( "output = " + output );

Parsing, if you insist, against my advice.

output = 20 Jul

String input = "20 Jul" ;
MonthDay mdParsed = MonthDay.parse( input , f  );

System.out.println( "mdParsed = " + mdParsed );

mdParsed = --07-20

You can generate a LocalDate from that MonthDay.

LocalDate ld = md.atYear( 2022 ) ;

ld.toString(): 2022-07-20

You can parse a date value using the same ideas.

All this has been covered many times on Stack Overflow. Search to learn more.

Sign up to request clarification or add additional context in comments.

1 Comment

@andrewJames Whoops, I misread simpleDateFormat as being the class. Thanks for correction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.