Don’t format your date for insertion into your SQL database. Assuming that your database column has datatype date
and you are using at least Java 8 and at least JDBC 4.2, just pass the LocalDate
to your PreparedStatement
as it is:
PreparedStatement insertStmt = myConnection.prepareStatement(
"insert into my_table(purchase_date) values (?)");
insertStmt.setObject(1, purchaseDate);
Your JDBC driver will take care of the rest. If using JPA, your JPA implementation will take care of it too.
If your column has char type (for example varchar(10)
) and you cannot change it, don’t invent your own format for it. Store the date in ISO 8601 format. LocalDate.toString()
produces this format.
String formattedDate = purchaseDate.toString();
System.out.println(formattedDate);
In my case output was:
2017-11-29
As an aside, for presentation to your user you shouldn’t invent your own format either. Rather rely on the built-in formats in Java. For example:
Locale turkish = Locale.forLanguageTag("tr");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(turkish);
String formattedDate = purchaseDate.format(dateFormatter);
System.out.println(formattedDate);
Output:
29.11.2017
What went wrong in your code?
There are two things wrong:
- You used lowercase
mm
. This means minute of hour, and since a LocalDate
doesn’t have a time of day in it, it threw the exception you saw. The message you got is pretty precise:
Unsupported field: MinuteOfHour
Instead you may use uppercase MM
for two-digit month.
- You need to pick up the format in the
String
returned from the format
method. The LocalDate
is immutable and therefore not affected by the method call. Also it cannot have a format in it. It’s just a date in the calendar.
Links
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…