2018-01-22T18:23:00.000Z is the ISO 8601 format for an instant. So you may just use Instant.parse("2018-01-22T18:23:00.000Z"). Catch a DateTimeParseException from the case where the string isn’t valid, either because it’s in the wrong format or the date and time is not valid (like month 13 or hour 25). It will accept 2018-01-22T18:23Z and 2018-01-22T18:23:00.000000000Z too. This should be OK for most purposes since it is still allowed within the ISO 8601 standard.
You may want to add a range check. Probably instants that are too far into the past or the future should be considered invalid for your application. Use Instant.isBefore() and/or Instant.isAfter().
不要使用正则表达式。对于那些维护您的代码的人来说,编写起来会很复杂,而阅读起来会非常非常复杂。如果您确实需要更详细的语法验证,请使用Akshay Batra的答案中DateTimeFormatter已经提到的。
| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |