- Choose the java.time class appropriate to your input string.
- Attempt to parse using the
parse method.
- 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.