java.time
You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
For a date-only value, use a date-only class: LocalDate
.
Define your formatting pattern with the DateTimeFormatter
class. Search Stack Overflow for many more discussions and examples, as this has been covered many many times.
When parsing, trap for DateTimeParseException
to determine if invalid.
String input = "22/02/2-19";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = null;
try {
ld = LocalDate.parse( input , f );
System.out.println( "VALID: " + ld.toString() );
} catch ( DateTimeParseException e ) {
System.out.println( "INVALID: " + input );
e.printStackTrace();
}
INVALID: 22/02/2-19
java.time.format.DateTimeParseException: Text '22/02/2-19' could not be parsed at index 6…
About java.time
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.