验证 ISO-8601 输入字符串

Validating ISO-8601 input string

我将使用 ISO-8601 格式的 String -:20170609T184237Z

什么是

的最佳方式
  1. 验证输入字符串
  2. 转换成毫秒字符串

我能想到的唯一方法是创建一个 DateTime 对象,然后从那里将其转换为毫秒,然后 String。有没有更好的方法?

我假设你的意思是 没有 -:。不,你解析成一些适当的日期时间对象并转换为毫秒的方法很好而且很标准,没有比这更好的了。

您打算使用 Joda-Time 吗?您可能需要再考虑一下。 Joda-Time 主页显示

Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

JSR-310 也被反向移植到 Java 6 和 7,因此我建议优先使用该反向移植而不是 Joda-Time。

以下内容可能超出您的要求。我建议这样的方法:

/**
 * 
 * @param dateTimeString String in 20170609T184237Z format
 * @return milliseconds since the epoch as String
 * @throws IllegalArgumentException if the String is not in the correct format
 */
private static String isoToEpochMillis(String dateTimeString) {
    try {
        OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString,
                DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX"));
        if (! dateTime.getOffset().equals(ZoneOffset.UTC)) {
            throw new IllegalArgumentException("Offset is not Z");
        }
        return String.valueOf(dateTime.toInstant().toEpochMilli());
    } catch (DateTimeException dte) {
        throw new IllegalArgumentException("String is not in format uuuuMMddTHHmmssZ",
                                           dte);
    }
}

我们这样称呼它:

    String milliseconds = isoToEpochMillis("20170609T184237Z");
    System.out.println(milliseconds);

这会打印

1497033757000

我不知道你想要多严格的验证。您的示例字符串具有 Z 时区;如您所见,我需要 UTC 时区,但也会接受例如 20170609T184237+00。如果那个 必须 Z,我认为你需要使用 dateTimeString.endsWith("Z").