javatimestamp

conversion from string to TimeStamp data type


i want to convert this : 17:26:54 to a TimeStamp data type. I need to enter it into a database. How do i do this? i have the data in a string variable i'm using java. I'm extracting this data from another source and i need to push it into a databse, in which the column for time stamp is defined to be of the type TimeStamp. I'm using JDBC to push data from the java program to MySQL. So i need a solution to convert the string : 17:26:54 to the timeStamp datatype so that it can be entered into the database without throwing an sql exception error.

edit: I do not need the date part of the timeStamp because i do not use it anywhere in my computations, and neither do I have the option of extracting it from the source which is generating the time information.


Solution

  • Use PreparedStatement#setTime() or PreparedStatement#setTimestamp() to insert java.sql.Time or java.sql.Timestamp.

    To convert String to Date or Timestamp use SimpleDateFormat

    Sample code:

     String time="12/07/2014 17:26:54";
    
     SimpleDateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
     Date date=format.parse(time);
    

    If you try below sample code then default date will be Jan 1, 1970

     String time="17:26:54";
    
     SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
     Date date=format.parse(time);
    

    How to convert Java date to SQL date?

     java.util.Date javaDate=new java.util.Date();
     java.sql.Date sqlDate=new java.sql.Date(javaDate.getTime());
    

    How to insert it into database timestamp data type?

    Sample code:

    String time="17:26:54";
    
    SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
    Date date=format.parse(time);
    
    ...
    
    PreparedStatement stmt = conn
            .prepareStatement("insert into test(message,time) values(?,?)");
    stmt.setString(1, "This is message");
    stmt.setTimestamp(2, new java.sql.Timestamp(date.getTime()));
    stmt.executeUpdate();
    

    Find complete sample code