[英]How to validate the DateTime string format “2018-01-22T18:23:00.000Z” in Java?
I need to validate in my code if the format of the DateTime
string 2018-01-22T18:23:00.000Z
is a valid one or not. 我需要在我的代码中验证
DateTime
字符串2018-01-22T18:23:00.000Z
是否有效。
Regex solution or any other solution is fine.Can someone help me doing this? 正则表达式解决方案或任何其他解决方案都可以,有人可以帮我吗?
2018-01-22T18:23:00.000Z
is the ISO 8601 format for an instant. 2018-01-22T18:23:00.000Z
是即时的ISO 8601格式。 So you may just use Instant.parse("2018-01-22T18:23:00.000Z")
. 因此,您可以只使用
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). 如果字符串格式错误或日期和时间无效(例如,第13个月或第25小时),则从字符串无效的情况下捕获
DateTimeParseException
。 It will accept 2018-01-22T18:23Z
and 2018-01-22T18:23:00.000000000Z
too. 它将也接受
2018-01-22T18:23Z
和2018-01-22T18:23:00.000000000Z
。 This should be OK for most purposes since it is still allowed within the ISO 8601 standard. 对于大多数目的,这应该可以,因为在ISO 8601标准中仍然允许这样做。
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()
. 使用
Instant.isBefore()
和/或Instant.isAfter()
。
Don't use a regular expression. 不要使用正则表达式。 It will be complicated to write and very, very complicated to read for those maintaining your code.
对于那些维护您的代码的人来说,编写起来会很复杂,而阅读起来会非常非常复杂。 If you do need more detailed syntax validation, use a
DateTimeFormatter
as already mentioned in Akshay Batra's answer . 如果确实需要更详细的语法验证,请使用Akshay Batra的答案中已经提到的
DateTimeFormatter
。
Create a String called "format", and put the required format there. 创建一个名为“ format”的字符串,然后在其中放置所需的格式。 After that try below code and check if dt returns anything
之后,尝试下面的代码,并检查dt是否返回任何内容
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);//required format
LocalDateTime dt = formatter.parse(oldstring);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.