I'm facing some problems in Eclipse with dates. I'm showing a date in a TextField with the format
dd/MM/yyyy
and I need to get the text from this textfield and parse it as a date to insert it in my database into a column of type DATE I'm using MySQL and it accepts dates as
yyyy-MM-dd
I tried really many options, both with LocalDate or the older Date, but didn't find a solution. Can someone please help? Thank you!
解决方案
Prior Java 8 approach
Firstly, after retrieving your string from your TextField, you should parse it to java.util.Date:
String text = textField.getText();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date textFieldAsDate = null;
try {
textFieldAsDate = sdf.parse(text);
} catch (ParseException pe) {
// deal with ParseException
}
Afterwards, you can convert your java.util.Date into a java.sql.Date, to store it into your MySQL database, like this:
sdf = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = java.sql.Date.valueOf(sdf.format(textFieldAsDate));
Java 8 approach
As mentioned by @BasilBourque, the Java date and time mechanism was provided by java.util.Date, java.util.Calendar, and java.util.TimeZone classes which are now legacy.
Therefore, in order to accomplish using Java 8 what was previously mentioned, one can do the following:
String text = textField.getText();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy");
java.time.LocalDate textFieldAsDate = java.time.LocalDate.parse(text, formatter);
Afterwards, in order to convert the LocalDate into a java.sql.Date, to store it into your MySQL database, it's possible to do the following:
java.sql.Date sqlDate = java.sql.Date.valueOf(textFieldAsDate);