How to convert String to Time and insert it MySQL
1 answer
You can use SimpleDateFormat
for analysis String
in this template java.util.Date
.
Assuming it is HH:mm
, you can do this:
String time = request.getParameter("time");
Date date = null;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
request.setAttribute("time_error", "Please enter time in format HH:mm");
}
Once an object java.util.Date
, you can store it in a column TIME
, convert it to java.sql.Time
and use PreparedStatement#setTime()
.
preparedStatement = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
preparedStatement.setTime(1, new Time(date.getTime()));
preparedStatement.executeUpdate();
+11
source to share