Converting a date a string to java.sql.Date format

user2335416 picture user2335416 · Jul 1, 2013 · Viewed 8.5k times · Source

I'm having an issue while trying to insert a date into an SQL server using Java:

//final String input = "20120823151034";
final String input = "06282013143533";

final DateFormat df = new SimpleDateFormat("MMddyyyyHHmmss");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
//c.add(Calendar.MILLISECOND, 1);
String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);  
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());  
System.out.println(sqltDate);

Here, I'm expecting the complete string being output as the year, month, day, hour, minutes, and seconds to be inserted into SQL server, but I'm only getting the year, month, and the date. What should I do to insert the date and the time into the database?

Answer

KhAn SaAb picture KhAn SaAb · Jul 1, 2013

check your DATA type in database either it should be Timestamp or Datetimefor this purpose you can use database function NOW() for current date and time.and convert your date into timestamp

  Timestamp timestamp = new Timestamp(new Date().getTime());

and insert this timestamp into database