See my Answer to a duplicate Question.
Using java.time
Use the modern java.time classes rather than the troublesome legacy date-time classes.
No need to use java.sql.Date
. That class is replaced by LocalDate
. The LocalDate class represents a date-only value without time-of-day and without time zone.
JDBC drivers that comply with JDBC 4.2 can deal directly with java.time types by calling:
- PreparedStatement::setObject
myPrepStmt.setObject( … , myLocalDate ) ;
- ResultSet::getObject
LocalDate ld = myResultSet.getObject( … , LocalDate.class );
For presentation of the LocalDate
to the user, generate a String for display in your user-interface. Use a DateTimeFormatter
to automatically localize. To localize, specify:
- FormatStyle to determine how long or abbreviated should the string be.
- Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l );
String output = zdt.format( f );
You can go the other direction as well, parsing an input string to get a date.
LocalDate ld = LocalDate.parse( input , f ) ;
Trap for the exception thrown if the user’s input is faulty or unexpected.
try{
LocalDate ld = LocalDate.parse( input , f ) ;
myPrepStmt.setObject( … , ld ) ;
} catch ( DateTimeParseException e ) {
… // Handle the error condition of faulty/unexpected input by user.
}
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.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
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.