Camus
Camus

Reputation: 845

How to convert String to Time and insert it MySQL

I have a JSP page, so the user can insert the time when he/she arrives and goes from the place manually. My question is: how can I convert that String, from the input box (JSP) to then insert it to query thus into my MySQL table. I am using Java - servlet. Thanks

Upvotes: 3

Views: 7768

Answers (1)

BalusC
BalusC

Reputation: 1109874

You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.

Assuming that it's HH:mm, then you can do so:

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 having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().

preparedStatement = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
preparedStatement.setTime(1, new Time(date.getTime()));
preparedStatement.executeUpdate();

Upvotes: 11

Related Questions