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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…