10

I want to convert java.util.Date to java.sql.Date but I want hours, minutes, and seconds as well but java.sql.Date can be used only to store date(no time) . I tried the below code but it is giving only year, month, and day for the java.sql.Date object.

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date parsed = format.parse("20110210120534");
System.out.println(format.parse("20110210120534"));
java.sql.Date sql = new java.sql.Date(parsed.getTime());
System.out.println("SQL date is= "+sql);

Current output:

2011-02-10

Desired output:

2011-02-10 12:05:34
Deepak Verma
  • 446
  • 1
  • 6
  • 15
  • Purpose of `java.sql.Date` precisely to store only informations about date, not about time (we have `java.sql.Time` for that). What are you really trying to achieve? Why are you want to use `java.sql.Date` instead of `java.util.Date`? – Pshemo Apr 01 '15 at 14:01
  • 4
    Use `java.sql.Timestamp` instead of `java.sql.Date` if you want more precision. – user432 Apr 01 '15 at 14:04
  • Thanks, I used Timestamp to resolve this problem. – Deepak Verma Apr 02 '15 at 07:11
  • Possible duplicate of [How to convert java.util.Date to java.sql.Date?](https://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date) – Vadzim Jun 28 '17 at 10:04
  • @Vadzim I had to search quite a bit to find the SQL part in that question / answer and then I had to look for time handling as well. I've changed the title instead of voting to close to indicate that this is specific for the time stored in `java.util.date`. – Maarten Bodewes Jun 28 '17 at 10:54

2 Answers2

17

The java.sql.Date type is used to store only date (no time) information, as it maps to the SQL DATE type, which doesn't store time. What its toString() method does is:

Formats a date in the date escape format yyyy-mm-dd.

To achieve the desired output you can use java.sql.Timestamp, which stores date and time information, mapping to the SQL TIMESTAMP type. Its toString() method outputs what you need:

Formats a timestamp in JDBC timestamp escape format: yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds.

Example:

java.text.DateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date date = format.parse("20110210120534");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp); // prints "2011-02-10 12:05:34.0"
ericbn
  • 10,163
  • 3
  • 47
  • 55
5

As other folks said, you need to use java.sql.TimeStamp.

public class Test {
        public static void main(String[] args) {
            java.util.Date date = new java.util.Date();
            java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(date.getTime());
            System.out.println("util-date:" + date);
            System.out.println("sql-timestamp:" + sqlTimeStamp );

        }

}

http://tutorials.jenkov.com/java-date-time/java-sql-date.html

geekprogrammer
  • 1,108
  • 1
  • 13
  • 39