-1

I have a String value which I need to convert into time and save it in the MySQL.[The column's datatype is time in the database table] The examples of String values that I might encounter to convert into time object are:

String time = "5:32 PM";

String time = "12:00 AM";

String time = "11:43 PM";

I browsed for few examples which pulled the time from the Date object but couldn't find an apt example, such as in this case to convert it from a plain string. The main reason I need to convert it to time is to save it in the mysql.

Community
  • 1
  • 1
Arun
  • 1,176
  • 5
  • 20
  • 48

1 Answers1

3

You can convert it to java.sql.Date as :

String str = "5:32 PM";
DateFormat formatter = new SimpleDateFormat("hh:mm a");
java.util.Date date = (java.util.Date)formatter.parse(str);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());

If you need java.sql.Time , then :

java.sql.Time time = new java.sql.Time(date.getTime());

And then use PreparedStatement#setTime().

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • `java.sql.Date` does not store time, you should use `java.sql.Time` or `java.sql.Timestamp`. Still, the best would be using plain `java.util.Date` since these three classes from `java.sql` package extend from it. – Luiggi Mendoza Jul 25 '13 at 15:07
  • @LuiggiMendoza Please add that to the answer , that is valuable comment :) – AllTooSir Jul 25 '13 at 15:09