1

I want to use the following ISO 8601 Format(Date and time with timezone) : yyyy-MM-ddTHH:mm:ss.SSSZ

To verify if the string date is valid or not.

I have as input a String date

String dateRight = "2017-12-25T13:01:59.123-0700"
String date2Right = "2017-12-25T13:01:59.123Z"

I want to check if these dates are in the right format that I mentioned above.

So far, I tried to use ZoneDateTime, LocalDateTime, DateTimeFormatter but I am not sure how to accomplish this.

0

1 Answer 1

2
  1. Choose the java.time class appropriate to your input string.
  2. Attempt to parse using the parse method.
  3. Trap for DateTimeParseException.

The exception is thrown (a) if the inout text is malformed or (b) if its contents are nonsensical such as day of month being 32.

For your second example input, use Instant. That class represents a moment as seen in UTC. The Z on the end of your input means an offset from UTC of zero hours-minutes-seconds. Pronounced “Zulu”.

If your input text complies with the ISO 8601 standard, then no need to define a formatting pattern.

try {
    Instant instant = Instant.parse( "2017-12-25T13:01:59.123Z" ) ;
} catch ( DateTimeParseException e ) {
    …
}

For your first example string, use OffsetDateTime. Your offset omitted the COLON character delimiter between the hours and minutes of the offset. So you’ll need to define a formatting pattern using DateTimeFormatter class. Search Stack Overflow, as this has been covered many times already.

Use ZonedDateTime if the input contains a date, time, and a time zone in the format of Continent/Region such as Asia/Tokyo Or Africa/Casablanca.

The ZonedDateTime class will attempt a guess at a 2-4 character pseudo-zone, but those are not standardized and are not even unique! Values such as CST and IST should only be used in localization for presentation, never for data exchange.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.