java.text.ParseException: unparseable date: "2/9/2016 10:30:00 AM (GMT-05:00) Eastern Time (US &



我在尝试解析此日期时遇到异常:

"2/9/2016 10:30:00 AM (GMT-05:00( 东部时间(美国和加拿大("代码

DateFormat format = new SimpleDateFormat("d/m/yyyy HH:mm:ss aaa zzz", Locale.ENGLISH); 
format.parse("2/9/2016 10:30:00 AM (GMT-05:00) Eastern Time (US & Canada)");

您在当月使用了m,这是错误的。您必须在月份使用M,在分钟中使用m

我还建议您使用 日期时间格式化程序 而不是使用过时的SimpleDateFormat。查看此项以了解有关现代日期/时间 API 的更多信息。

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d/M/yyyy hh:mm:ss a (zzz)")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse("2/9/2016 10:30:00 AM (GMT-05:00)", formatter);
System.out.println(zdt);
}
}

输出:

2016-09-02T10:30-05:00[GMT-05:00]

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d/M/yyyy hh:mm:ss a (zzz)")
.appendLiteral(" Eastern Time (US & Canada)")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse("2/9/2016 10:30:00 AM (GMT-05:00) Eastern Time (US & Canada)",
formatter);
System.out.println(zdt);
System.out.println(formatter.format(zdt));
}
}

输出:

2016-09-02T10:30-05:00[GMT-05:00]
2/9/2016 10:30:00 AM (GMT-05:00) Eastern Time (US & Canada)

您正在解析的日期与格式不匹配,

m 代表一分钟,M 代表月份,这将起作用,

DateFormat format = new SimpleDateFormat("d/M/yyyy HH:mm:ss aaa (zzz)", Locale.ENGLISH);
format.parse("2/9/2016 10:30:00 AM (GMT)");

您可以使用Java SimpleDateFormat Online Tester为日期:2/9/2016 10:30:00 AM (GMT-05:00( 东部时间(美国和加拿大(创建格式。

希望这对你有帮助,

java.time

像其他人一样,我建议您使用java.time,现代Java日期和时间API,用于日期和时间工作。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/u h:mm:ss a (OOOO)", Locale.ENGLISH);
String stringToParse = "2/9/2016 10:30:00 AM (GMT-05:00) Eastern Time (US & Canada)";
ParsePosition pp = new ParsePosition(0);
TemporalAccessor parsed = formatter.parse(stringToParse, pp);
OffsetDateTime dateTime = OffsetDateTime.from(parsed);
System.out.println(dateTime);

输出为:

2016-09-02T10:30-05:00

Eastern Time (US & Canada)不被视为 Java 使用的时区数据库中的时区,因此我们不能使用DateTimeFormatterSimpleDateFormat解析这部分字符串。为了仅解析字符串的一部分,我使用的是接受ParsePositionDateTimeFormatter.parse方法。如果需要,我们可以在之后使用ParsePosition来确定已解析了多少字符串。

您的代码中出了什么问题?

  • ParseException的原因是(GMT-05:00)与格式模式字符串中的zzz不匹配。或者更准确地说,格式模式不包括要分析的字符串中的圆括号。
  • 正如其他人所说,您需要在格式模式中大写M月份。小写m为分钟。这将导致不正确的结果。虽然SimpleDateFormat应该仅以此错误为由抛出例外,但它没有。
  • 您最终需要小写hhh在 01 到 12 的 AM 或 PM 内一小时。大写HH表示一天中的小时从 00 到 23。

链接

Oracle 教程:日期时间解释如何使用 java.time。

相关内容

最新更新