Jeevika
Jeevika

Reputation: 165

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?

Upvotes: 3

Views: 3210

Answers (2)

Anonymous
Anonymous

Reputation: 86276

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:23:00Z 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. It will require that seconds are present, though: It will not accept 2018-01-22T18:23Z. A quick solution if you need this is OffsetDateTime.parse("2018-01-22T18:23Z").toInstant(). It doesn’t validate that the offset in the string is Z, though.

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, including the case where you need to accept minutes precision with no seconds, use a DateTimeFormatter as already mentioned in Akshay Batra’s answer.

Upvotes: 10

Akshay Batra
Akshay Batra

Reputation: 137

Create a String called "format", and put the required format there. After that try below code and check if dt returns anything

DateTimeFormatter formatter = DateTimeFormat.forPattern(format);//required format
LocalDateTime dt = formatter.parse(oldstring);

Upvotes: 1

Related Questions