提问人:Manisha Biswas 提问时间:6/28/2023 更新时间:6/28/2023 访问量:82
获取 java.time.format.DateTimeParseException:无法在索引 17 处解析文本“2020 年 12 月 5 日上午 10:00:00”(太平洋夏令时)
Getting java.time.format.DateTimeParseException: Text 'December 05, 2020 at 10:00:00 AM PDT' could not be parsed at index 17
问:
我正在尝试在IntelliJ IDE中运行以下代码并获得解析异常,而该代码适用于在线Java编译器。有人可以帮我了解我做错了什么吗?
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class MyClass {
public static void main(String args[]) {
String slot = "December 05, 2020 at 10:00:00 AM PDT";
String locale = "en-US";
String timezone = "America/Los_Angeles";
long epoch = convertDateToLong(slot, locale, timezone);
System.out.println(epoch);
}
private static long convertDateToLong (String dateTimeString, String locale, String timezone) {
ZoneId zoneId = ZoneId.of(timezone);
String offsetId = ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(timezone)).getOffset().toString();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(zoneId).withLocale(Locale.forLanguageTag(locale));
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);
long epoch = localDateTime.toEpochSecond(ZoneOffset.of(offsetId));
return epoch * 1000;
}
}
答: 暂无答案
评论
ZonedDateTime
DateTimeFormatter.ofPattern("MMMM dd, uuuu 'at' hh:mm:ss a z", Locale.ENGLISH)
Locale.US
en_US
en-US