mv93
mv93

Reputation: 285

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.

Upvotes: 0

Views: 5983

Answers (3)

Braj
Braj

Reputation: 46841

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

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201409

Per your comments

doesnt matter to me because i dont need date

Make it a colum of TIME type. Then per the getting started with JDBC guide,

java.sql.Time for SQL TIME information. The year, month, and day fields of the java.util.Date base class are set to 1970, January, and 1. This is the "zero" date in the Java epoch.

The Time constructor,

long millis = (hour * 3600 * 1000) + (minutes * 60 * 1000) + (seconds * 1000);
java.sql.Time time = new java.sql.Time(millis);

Upvotes: 0

user784540
user784540

Reputation:

Consider DateFormat class to convert string to a java.util.Date instance.

java.sql.Timestamp can be constructed with long date representation, which can be get from java.util.Date class instance via getTime() method.

Upvotes: 0

Related Questions