Reputation: 1
I tried to get the value of html input type "date" using request.getParameter() in servlet class, converted it into java date in JDBC Class, then to sql date format.
but there is this exception java.text.ParseException: Unparseable date.
This is the HTML tag for date
input type="date" name="BirthDate"
This is the servlet code to get value from HTML page
String bDate = request.getParameter("BirthDate");
This is the JDBC Class code to convert it
String bbd = user.getBDate();
DateFormat df = new SimpleDateFormat("dd/MM/yyy");
java.util.Date bbDate = df.parse(bbd);;
java.sql.Date bDate = new java.sql.Date(bbDate.getTime());
Upvotes: 0
Views: 5712
Reputation: 338574
myPreparedStatement.setObject( // As of JDBC 4.2, pass java.time objects to your database.
… ,
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.parse( // Convert text to a `LocalDate` object.
"23/01/2018" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Specify formatting pattern to match user input.
) // Returns a `LocalDate` object.
)
Use only java.time classes. Never use java.util.Date
, java.sql.Date
, Calendar
, SimpleDateFormat
, etc.
String input = "23/01/2018" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
As of JDBC 4.2, we can directly exchange java.time objects with the database.
myPreparedStatement.setObject( … , ld ) ;
Retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
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.
Upvotes: 1