How to convert String to Time and insert it MySQL

I have a JSP page so the user can insert the times when they arrive and leave the location manually. My question is, how can I convert this string from an input field (JSP) and then insert it into a query in my MySQL table. I am using Java Servlet. Thanks to


source to share

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()));




All Articles