如何在Java中验证DateTime字符串格式“ 2018-01-22T18:23:00.000Z”?

Jee*_*eev 0 java regex string datetime

我需要在我的代码中验证DateTime字符串的格式2018-01-22T18:23:00.000Z是否有效。

正则表达式解决方案或任何其他解决方案都可以,有人可以帮我吗?

Ole*_*.V. 5

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已经提到