ゲオルギオス:
以下の文字列から、私はLOCALDATEかのLocalDateTimeを取得したいです。
2019年1月1日午前12:00:00
私はすでに、次のコードを試してみましたが、私は次のエラーを取得しています:
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
方法は、私は最後に、のようになる、日付を持っていると思います
- 2019年1月1日。LOCALDATE
- 2019年1月1日。(24時間)12:00 localdateti
これさえ可能ですか?代わりにやり過ぎ正規表現の使用でしょうか?
トーマスPötzsch:
そこにあなたのコードにいくつかの問題がありますが、私はここで働いて解決策を提案します。
HH
日の時間は、(あるいない時間0-12hh
)- あなたはDateTimeFormatterBuilderを使用する必要があります
- あなたは適切なロケールを使用し、おそらく必要があります
GERMANY
代わりに、GERMAN
- 月の名前は次のように表現され
L
ていないとして、M
- ドイツ語ロケールの用途
vorm.
とnachm.
の代わりに、AM
とPM
- >迅速な解決策は、用語を交換することです
すべて一緒にそれを置くことはこれで私たちを残します:
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);
}
}
誰もがハンドリングに異なるアプローチがある場合はAM
/ vorm.
-dilemmaを、私はそれを見て喜んでいるだろう!