Ihsan Haikal
Ihsan Haikal

Reputation: 1215

Failed String Parsing to LocalDateTime using DateTimeFormatter

I am trying to parse a simple string [08/May/2020:09:14:05 +0000] to LocalDateTime using DateTimeFormatter and LocalDateTime but it seems that it does not work for some reasons. I have tried different changes to the format like DD, hh, X, x, or Z but it doesn't work.

Here is the code:

String log = "[08/May/2020:09:14:05 +0000]";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[d/MMM/yyyy:HH:mm:ss x]");
LocalDateTime odt = LocalDateTime.parse(log, fmt);
System.out.println(odt);

Any guess?

Upvotes: 2

Views: 783

Answers (2)

Anonymous
Anonymous

Reputation: 86149

All credit goes to Andreas. His suggestion in the comments is good enough to be posted as an answer.

    String log = "[08/May/2020:09:14:05 +0000]";
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("'['dd/MMM/uuuu:HH:mm:ss xx']'", Locale.US);
    LocalDateTime odt = LocalDateTime.parse(log, fmt);
    System.out.println(odt);

Output is:

2020-05-08T09:14:05

In the format pattern string the square brackets [ and ] are (usually) used to enclose optional parts of the format. Since you want to specify that literal square brackets are in the date-time string, enclose them in apostrophes in the format pattern string. This cancels the meaning that the brackets have otherwise.

Also use xx for UTC offset with hours and minutes without colon such as +0000.

Finally always specify locale when the string includes locale sensitive parts such as a month abbreviation. In this case I think that any English-speaking locale will work, including Locale.ENGLISH, Locale.ROOT, Locale.UK, Locale.US and many others.

Upvotes: 2

tinymothbrain
tinymothbrain

Reputation: 412

Get rid of the square brackets. And add another x to the timezone format.

log = log.replaceAll("\\[", "");
log = log.replaceAll("]", "");
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[d/MMM/yyyy:HH:mm:ss xx]");

You can add the brackets back in with

System.out.println("[" + odt + "]");

Also, you may want to add another 'd' to the day of the month.

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[dd/MMM/yyyy:HH:mm:ss xx]");

Upvotes: 0

Related Questions