4

For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).

How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.

I tried the following:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
n00b1990
  • 1,189
  • 5
  • 17
  • 25

4 Answers4

7

The problem is here:

java.sql.Date date = new java.sql.Date(javaDate.getTime());

java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:

java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.

    String input = "06/10/2013 18:29:09";
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
    java.util.Date dt = sdf.parse(input);
    java.sql.Date dtSql = new java.sql.Date(dt.getTime());
NRJ
  • 1,064
  • 3
  • 15
  • 32
0

If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.

Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

Best Regards.

Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51
  • Instead of linking to a tutorial, it would be better to provide an example. Usage of `SimpleDateFormat` is no rocket science. – Luiggi Mendoza Jun 02 '14 at 14:50
0

Here's a simple demo. In a Database table like this.

You can insert into it like this.

 //the SQL statement for creating the database table
 create table user(id, integer primary key, username varchar(100), date_created varchar(100));

 //the java code to insert into the table created above.
 try{
 String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
 String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
 int done = statement.executeUpdate(sql);
 if(done > 0)
    //inserted
 else
   //not inserted.
 }catch(java.sql.SQLException e){}

Hope that helps

Zuko
  • 2,764
  • 30
  • 30