I have a Calendar instance, parsed from XSD datetime via the javax.xml.bind.DatatypeConverter.parseDateTime method by JAXB.
At runtime, i\'m in a web service, and i want
OffsetDateTime.parse( "2015-07-35T09:32:05.543+02:00" )
… catch ( DateTimeParseException e )
The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9.
Likewise, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
OffsetDateTime & DateTimeParseExceptionTo determine invalid date-time string, attempt to parse and trap for exception. Given that your inputs have an offset-from-UTC but not a time zone, parse as OffsetDateTime objects. Invalid inputs throw DateTimeParseException.
String inputGood = "2015-07-30T09:32:05.543+02:00" ;
String inputBad = "2015-07-35T09:32:05.543+02:00" ;
try{
// Good
OffsetDateTime odtGood = OffsetDateTime.parse( inputGood ) ;
System.out.println( "odtGood.toString(): " + odtGood ) ;
// Bad
OffsetDateTime odtBad = OffsetDateTime.parse( inputBad ) ;
System.out.println( "odtBad.toString(): " + odtBad ) ;
} catch ( DateTimeParseException e ) {
System.out.println( e ) ;
}
See code run live at IdeOne.com.
odtGood.toString(): 2015-07-30T09:32:05.543+02:00
java.time.format.DateTimeParseException: Text '2015-07-35T09:32:05.543+02:00' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 35
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.