LOCALDATEへの特別な文字列

ゲオルギオス:

以下の文字列から、私は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:

そこにあなたのコードにいくつかの問題がありますが、私はここで働いて解決策を提案します。

  1. HH日の時間は、(あるいない時間0-12 hh
  2. あなたはDateTimeFormatterBuilderを使用する必要があります
  3. あなたは適切なロケールを使用し、おそらく必要がありますGERMANY代わりに、GERMAN
  4. 月の名前は次のように表現されLていないとして、M
  5. ドイツ語ロケールの用途vorm.nachm.の代わりに、AMPM- >迅速な解決策は、用語を交換することです

すべて一緒にそれを置くことはこれで私たちを残します:

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を、私はそれを見て喜んでいるだろう!

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=333227&siteId=1
おすすめ