0

我在从字符串中解析日期时遇到问题

这是我的约会

String startedFrom = "Fri,+31+Dec+3999+23:00:00+GMT"

DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss z", Locale.ENGLISH);

Date result =  df.parse(startedFrom);

我做错了什么?

我得到异常

java.text.ParseException: Unparseable date: "Fri,+31+Dec+3999+23:00:00+GMT"
4

2 回答 2

1
DateFormat df = new SimpleDateFormat("EEE,'+'dd'+'MMM'+'yyyy'+'kk:mm:ss'+'z",
        Locale.ENGLISH);

但是,如果该startedFrom值实际上是添加到 URL 的 URL 编码参数(如在具有 GET 方法的 HTML 表单中),那么'+'将作为 space 到达' ',因此您的原始格式将是正确的。

于 2018-01-19T07:04:39.207 回答
1

首先,为此使用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]

根据您需要的日期时间,您可以将其转换为OffsetDateTimeInstant通过调用result.toOffsetDateTime()or result.toInstant()

于 2018-01-19T11:01:20.157 回答