Datetime 正在分析java 8中的时间字符串-ClockHourOfAmPm的值无效
我正在尝试转换属性文件中具有给定时间的时区Datetime 正在分析java 8中的时间字符串-ClockHourOfAmPm的值无效,datetime,java-8,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 = "
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中。在上面的代码中,我已经硬编码了它。它是如何工作的?如何使用我给出的时间-日期格式?您应该将
日期\u格式更改为:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
如果参考文档,您会看到如下描述:
每天小时数(0-23)
在您的情况下,您将从属性文件中以hour of day
(HH
)而不是clock hour of am pm
(HH a
)格式提供小时。由于13
(>12)对于没有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";
为什么不能将DATE\u格式更改为接受HH
,而不是HH
?Hi将其更改为HH有效。我想hh和hh的意思是一样的。不是吗?非常感谢。我被这个问题困扰了一段时间……我的列表没有按预期排序,这就是问题所在。谢谢