这个问题在这里已经有了答案:
How to set 24-hours format for date on java?
(10 个回答)
2年前关闭。
我正在尝试在我的属性文件中转换具有给定时间的时区。
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));
}
}
所以我收到错误:
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)
我从属性文件中获取的日期时间中没有 AM/PM 值。该值存储在字符串 ds 中。在上面的代码中,我对其进行了硬编码。它是如何工作的?如何使其与我提供的时间日期格式一起使用?
最佳答案
您应该更改 DATE_FORMAT
到:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
如果您引用 DateTimeFormatter docs 你看到的描述如下:
H hour-of-day (0-23)
在您的情况下,您将小时提供为
hour-of-day
( HH
) 而不是在 clock-hour-of-am-pm
( hh a
) 格式来自您的属性文件。并作为 13
( > 12) 不是 clock-hour-of-am-pm
的可接受值没有 AM/PM 你会得到一个异常(exception)。如果你想要它在
clock-hour-of-am-pm
您需要将格式更改为:private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
并在日期字符串中添加 AM/PM 信息:
String ds = "2019-03-18 12-14-48 AM";
关于datetime - 在 java 8 中解析时间字符串 - ClockHourOfAmPm 的值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228703/