Yes, yyyy-MM-dd is the ISO 8601 format for a date without time of day and without time zone.
To store into an SQL database using either a JDBC 4.2 or later driver or a modern JPA implementation such as Hibernate 5, you have got nothing to use a Date
object for (no matter if you meant java.util.Date
or java.sql.Date
). I recommend that instead you use java.time, the modern Java date and time API. The class to use for a date without time of day is LocalDate
. And you can store one into your database without any conversion.
LocalDate
parses ISO 8601 format as its default, that is, without any explicit formatter:
String receivedString = "1962-11-27";
LocalDate dateOfBirth = LocalDate.parse(receivedString);
System.out.println("Date of birth is " + dateOfBirth);
LocalDate
also gives ISO 8601 format back when we print it:
Date of birth is 1962-11-27
I haven’t given you the full story yet, though. yyyy-MM-dd is the extended format that is by far most often used. There is also a basic format that is compacter in that it leaves out the hyphens: yyyyMMdd. I suggest that you insist on getting your date string in the extended format. If you cannot do that, you will have to specify a formatter for parsing:
String receivedString = "19621127";
LocalDate dateOfBirth = LocalDate.parse(
receivedString, DateTimeFormatter.BASIC_ISO_DATE);
This will give you a LocalDate
equal to and indistinguishable from the one we had before.
To save into your database using JDBC:
PreparedStatement pStmt
= yourDatabaseConnection.prepareStatement(
"insert into your_table (date_of_birth) values (?);");
pStmt.setObject(1, dateOfBirth);
int insertedRows = pStmt.executeUpdate();
Note the use of setObject()
, not setDate()
.
Links