Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a Date as SQL parameter in Java without losing the time part? [duplicate]

Tags:

java

sql

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());
like image 221
n00b1990 Avatar asked Sep 05 '25 01:09

n00b1990


1 Answers

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:

  • Date vs TimeStamp vs calendar?
like image 145
Luiggi Mendoza Avatar answered Sep 06 '25 14:09

Luiggi Mendoza