首页 > 解决方案 > 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);

最后,我希望约会的方式就像

这甚至可能吗?相反,使用正则表达式会不会过大?

标签: javadatelocaldate

解决方案


您的代码存在一些问题,但我将在这里提出一个可行的解决方案:

  1. HH是一天中的小时,而不是 0-12 小时(即hh
  2. 你应该使用 DateTimeFormatterBuilder
  3. 您应该使用正确的语言环境,可能GERMANY而不是GERMAN
  4. 月份的名称表示为L,而不是M
  5. 德语语言环境使用vorm.andnachm.而不是AMand 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,我会很高兴看到它!


推荐阅读