Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
818 views
in Technique[技术] by (71.8m points)

regex - 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.

Regex solution or any other solution is fine.Can someone help me doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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().

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...