LocalDate 的特殊字符串

Special string to 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);

我想要的日期最终会像

这可能吗?相反,使用正则表达式会不会有点矫枉过正?

您收到错误是因为您试图将 LocalDateTime 格式解析为 LocalDate。

如果您有完整的 LocalDateTime,则不需要单独的 LocalDate。如果有需要,LocalDateTime 中还有一个 toLocalDate() 方法。

    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)");

你的代码有一些问题,但我会在这里提出一个可行的解决方案:

  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.-困境,我将很高兴看到它!