如何处理Java 8 / JSR 310 / threeten.org中ISO-8601时间戳中的“可选”T?

时间:2015-05-12 20:40:51

标签: java datetime java-8 java-time

在Java 8时代/ JSR 310 / threeten.org backport ...

问:如何在日期部分和时间部分之间用'T'或空格'解析ISO-8601时间戳?

时间戳的ISO-8601格式指定用于将日期规范与时间规范分开的文字“T”:

2015-05-12T15:42:00.123

许多应用程序使用空格''而不是'T'生成此格式的时间戳。参考文献表明ISO-8601允许通过双方协议

2015-05-12 15:42:00.123

因为我从多个来源摄取数据,我想要允许'T'或空格''。

我观察到模式字符串允许指定可选组件,但我没有看到任何方式在模式字符串中指定“选择”......

问:有没有办法在JSR 310模式字符串中“选择一个完全一个”?

我能够通过构造一个带有两个可选模式的DateTimeFormatter来实现这个目的:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
    .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    .optionalStart().appendPattern("yyyy-MM-dd HH:mm:ss.SSS").optionalEnd()
    .toFormatter();

看到optionalStart()和optionalEnd()导致我:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
    .appendPattern("[yyyy-MM-dd HH:mm:ss.SSS][yyyy-MM-dd'T'HH:mm:ss.SSS]")
    .toFormatter();

但是,我不相信这是处理这种情况的正确的方法......

问:处理多个DateTime模式的最佳实践解决方案是什么?

提前致谢。

1 个答案:

答案 0 :(得分:6)

Cleanse Your Input Data

My own practice:

  • Include the =IFERROR(MATCH(A2,'2_4'!$A$1:$A$79145,0),"") by default.
  • Clean the input data before calling java.time (or Joda-Time).

When accepting text from outside my own code, I never trust such external inputs. Heck, I don’t even trust my own internal inputs. I always put such data through a cleaner. As part of that cleaning I replace any SPACE character in any expected ISO 8601 string with a T.

T

I also make a habit of calling the Google Guava library to trim whitespace from the input string. See this Answer for details.

And check for NULL, non-printing, and other inappropriate characters. Those non-printables make for nasty bugs.

Only after that do I call the date-time libraries ( Joda-Time or java.time ).

Trap Parsing Exception

Also, you should use a try-catch to trap for the parsing exception to more gracefully handle when the date-time input string fails to meet your expectations.