在 java 8 中解析时间字符串 - ClockHourOfAmPm 的值无效

Gro*_*oot 3 datetime java-8

我正在尝试在我的属性文件中转换具有给定时间的时区。

 package test1;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class TimeZoneConversion {

private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";

public static void main(String[] args) {

    String ds = "2019-03-18 13-14-48";
    LocalDateTime ldt = LocalDateTime.parse(ds, DateTimeFormatter.ofPattern(DATE_FORMAT));
    System.out.println("ldt : "+ldt);

    ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
    System.out.println("TimeZone : " + singaporeZoneId);

    //LocalDateTime + ZoneId = ZonedDateTime
    ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
    System.out.println("Date (Singapore) : " + asiaZonedDateTime);

    ZoneId newYokZoneId = ZoneId.of("America/New_York");
    System.out.println("TimeZone : " + newYokZoneId);

    ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
    System.out.println("Date (New York) : " + nyDateTime);

    DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
    System.out.println("\n---DateTimeFormatter---");
    System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
    System.out.println("Date (New York) : " + format.format(nyDateTime));

}
Run Code Online (Sandbox Code Playgroud)

}

所以我收到错误:

 Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-18 13-14-48' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at test1.FirstClass.main(FirstClass.java:20)
Run Code Online (Sandbox Code Playgroud)

我从属性文件中获取的日期时间中没有 AM/PM 值。该值存储在字符串 ds 中。在上面的代码中,我对其进行了硬编码。它是如何工作的?如何使其与我提供的时间日期格式一起使用?

Ful*_*Guy 8

您应该将其更改DATE_FORMAT为:

 private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
Run Code Online (Sandbox Code Playgroud)

如果您参考DateTimeFormatter文档,您会看到如下描述:

H 小时 (0-23)

在您的情况下,您将小时作为hour-of-day( HH) 而不是clock-hour-of-am-pm( hh a) 格式从您的属性文件中提供。由于13( > 12) 不是可接受的值,因为clock-hour-of-am-pm如果没有 AM/PM,您将得到一个例外。

如果你想要它,clock-hour-of-am-pm你需要将格式更改为:

private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
Run Code Online (Sandbox Code Playgroud)

并在日期字符串中添加 AM/PM 信息:

String ds = "2019-03-18 12-14-48 AM";
Run Code Online (Sandbox Code Playgroud)