繁体   English   中英

是否有更好的方法将此时间戳格式化为ISO8601?

[英]Is there a better way to format this timestamp to ISO8601?

我有一个看起来像这样的时间戳: 2015-11-12T20:45:24+0000 这是由其他人的脚本生成的,据称该脚本使用UNIX date命令(可能是类似date -u +%Y-%m-%dT%H:%M:%S%z )。

但是 ,根据Java的DateTimeFormatter ,与此最接近的ISO 8601格式应为ISO_OFFSET_DATE_TIME ,其格式类似于: 2015-11-12T20:45:24+00:00 (请注意末尾的额外冒号 )。 如果我输入了我的时间戳版本,则解析器将无法处理它,但是如果我手动添加了冒号,则不会有任何问题。

我的问题是, 有没有更简单,更可靠/更可靠的方式来处理这些时间戳? 我得到的时间戳可能有也可能没有最后的冒号分隔分钟和秒,目前,我的代码中包含以下验证:

// We expect a colon at index length-3 (the colon delimits the hours:minutes of the timezone offset)
char colon = ':';
int expectedIndexOfColon = string.length() - 3;

// If that colon is not there, add it
if (string.lastIndexOf(colon) == expectedIndexOfColon) {
    return string;
} else {
    int substringIndex = string.length() - 2;
    return string.substring(0, substringIndex) + colon + string.substring(substringIndex);
}

这看起来很骇人,我想知道是否有更优雅的方式来处理这两种不同的格式。 我了解Joda-Time,但他们的解析器也拒绝了无冒号的时间戳(根据我的尝试)。 此外,Joda-Time建议无论如何java.time对Java 8使用Java的java.time

如果您的代码需要多种不同的格式,则需要适应这些差异。

一种常见的方法是将您期望的格式放入List某种数组中并对其进行迭代,以找到不会引发异常的格式

例如:

  • DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")可以解析2015-11-12T20:45:24+0000
  • DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz")可以解析2015-11-12T20:45:24+00:00

您可以使用类似...

public static LocalDateTime parse(String text, List<DateTimeFormatter> formats) {
    LocalDateTime ldt = null;
    for (DateTimeFormatter formatter : formats) {
        try {
            ldt = LocalDateTime.parse(text, formatter);
        } catch (DateTimeParseException e) {
            // Maybe log the failure if you're interested
        }
    }
    return ldt;
}

然后您可能会使用类似...

List<DateTimeFormatter> formats = new ArrayList<>(2);
formats.add(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
formats.add(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz"));
System.out.println(parse("2015-11-12T20:45:24+0000", formats));
System.out.println(parse("2015-11-12T20:45:24+00:00", formats));

哪个输出...

2015-11-12T20:45:24
2015-11-12T20:45:24

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM