Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store time from java.util.Date into java.sql.Date

Tags:

java

date

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
like image 756
Deepak Verma Avatar asked Apr 01 '15 13:04

Deepak Verma


People also ask

Does Java sql date Store time?

java.sql.DateStores hours, minutes. Seconds and milliseconds alone.

Does Java Util date have timestamp?

A thin wrapper around java. util. Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds.

How do I convert a date to a date in sql?

You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format).

What is the difference between Java Util date and Java sql date?

sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.


2 Answers

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

like image 84
geekprogrammer Avatar answered Sep 28 '22 02:09

geekprogrammer


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"
like image 39
ericbn Avatar answered Sep 28 '22 02:09

ericbn