Reputation: 1037
From the following String I want to get the LocalDate or LocalDateTime.
Jan 1, 2019 12:00:00 AM
I have already tried the following code but I am getting the following error:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy hh:mm:ss a"); // also with dd
formatter = formatter.withLocale(Locale.GERMAN);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
LocalDate localDate = LocalDate.parse(stringDate, formatter);
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jan 1, 2019 12:00:00 AM' could not be parsed at index 0
The way I would like to have the date, in the end, would be like
Is this even possible? Would be instead the use of regular expressions an overkill?
Upvotes: 1
Views: 1201
Reputation: 329
There are a few problems with your code, but I will propose a working solution here:
HH
is the hour of the day, not the hour 0-12 (which is hh
)GERMANY
instead of GERMAN
L
, not as M
vorm.
and nachm.
instead of AM
and PM
-> a quick solution is to replace the termsPutting it all together leaves us with this:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
class Scratch {
public static void main(String[] args) {
String stringDate = "Jan 1, 2019 11:00:00 PM";
stringDate = stringDate.replace("AM", "vorm.");
stringDate = stringDate.replace("PM", "nachm.");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("LLL d, yyyy hh:mm:ss a")
.toFormatter(Locale.GERMANY);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
LocalDate localDate = LocalDate.parse(stringDate, formatter);
}
}
If anybody has a different approach to handling the AM
/vorm.
-dilemma, I would be glad to see it!
Upvotes: 3
Reputation: 51
You're getting the error because you're trying to parse a LocalDateTime format into a LocalDate.
If you have the full LocalDateTime, you shouldn't need a separate LocalDate. If there is a need, there's also a toLocalDate() method within LocalDateTime.
String stringDate = "Jan 1, 2019 12:00:00 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy hh:mm:ss a"); // also with dd
formatter = formatter.withLocale(Locale.GERMAN);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
DateTimeFormatter firstOutputFormat = DateTimeFormatter.ofPattern("MM.DD.YY.");
String outputFirst = localDateTime.format(firstOutputFormat).concat(" LocalDate");
DateTimeFormatter secondOutputFormat = DateTimeFormatter.ofPattern("MM.DD.YY. HH.mm");
String outputSecond = localDateTime.format(secondOutputFormat).concat(" LocalDateTime (24h)");
Upvotes: 1