Java-解析日期(可选秒)

时间:2018-12-16 03:23:15

标签: java datetime parsing java.time

鉴于我要解析的日期:12月15日16:00 +01:00

使用此代码

    Map<Long, String> ordinalNumbers = new HashMap<>(42);
    ordinalNumbers.put(1L, "1st");
    ordinalNumbers.put(2L, "2nd");
    ordinalNumbers.put(3L, "3rd");
    ordinalNumbers.put(21L, "21st");
    ordinalNumbers.put(22L, "22nd");
    ordinalNumbers.put(23L, "23rd");
    ordinalNumbers.put(31L, "31st");
    for (long d = 1; d <= 31; d++) {
        ordinalNumbers.putIfAbsent(d, "" + d + "th");
    }

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
            .appendPattern(" MMM HH:mm[:ss] xxx")
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter().withLocale(Locale.ENGLISH);

    ZonedDateTime eventDate = ZonedDateTime.parse("15th Dec 16:00 +01:00", formatter);

但我总是得到

  

java.time.DateTimeException:无法从TemporalAccessor获取ZonedDateTime:{DayOfMonth = 15,MonthOfYear = 12,OffsetSeconds = 3600},ISO解析为类型为java.time.format.Parsed的16:00

您可以在此处在线试用:https://repl.it/repls/NaiveRegularEquation 请告诉我我做错了。

更新: 缺少的一年就是问题所在。

 DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
            .appendPattern(" MMM HH:mm[:ss] xxx")
            .parseDefaulting(ChronoField.YEAR, 2018)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter().withLocale(Locale.ENGLISH);

1 个答案:

答案 0 :(得分:2)

指定年份

ZonedDateTime需要年份字段,而您没有提供。

您可以设置默认值:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseDefaulting(ChronoField.YEAR_OF_ERA, ZonedDateTime.now().getYear()) // set default year
        .appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
        .appendPattern(" MMM HH:mm[:ss] xxx")
        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
        .toFormatter().withLocale(Locale.ENGLISH);