首先,为此使用java.time
及其DateTimeFormatter
类。SimpleDateFormat
臭名昭著的麻烦,并且与Date
班级一起早已过时。java.time
是现代 Java 日期和时间 API,使用起来更方便。
其次,Joop Eggen 在他的回答中是正确的,即您的字符串看起来像一个 URL 编码的参数,最初是Fri, 31 Dec 3999 23:00:00 GMT
. 这听起来更有可能,因为这是一种称为 RFC 1123 的标准格式,通常与 HTTP 一起使用。因此,用于获取 URL 参数的库应该为您对字符串进行 URL 解码。然后很简单,因为已经为您定义了要使用的格式化程序:
String startedFrom = "Fri, 31 Dec 3999 23:00:00 GMT";
OffsetDateTime result
= OffsetDateTime.parse(startedFrom, DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(result);
这打印
3999-12-31T23:00Z
如果您无法让您的库进行 URL 解码,请使用以下方法自行完成URLDecoder
:
String startedFrom = "Fri,+31+Dec+3999+23:00:00+GMT";
try {
startedFrom = URLDecoder.decode(startedFrom, StandardCharsets.UTF_16.name());
} catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF_16 is not supported — this should not be possible", uee);
}
现在按上述方式进行。
您当然也可以定义一个格式化程序来解析带有加号的字符串。不过,我不知道你为什么要这样做。如果你这样做,你只需要在格式模式字符串中也有它们:
DateTimeFormatter formatterWithPluses
= DateTimeFormatter.ofPattern("EEE,+d+MMM+yyyy+H:mm:ss+z", Locale.ROOT);
ZonedDateTime result = ZonedDateTime.parse(startedFrom, formatterWithPluses);
这次我们得到了一个ZonedDateTime
以 GMT 为时区的名称:
3999-12-31T23:00Z[GMT]
根据您需要的日期时间,您可以将其转换为OffsetDateTime
或Instant
通过调用result.toOffsetDateTime()
or result.toInstant()
。