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
java.sql.DateStores hours, minutes. Seconds and milliseconds alone.
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.
You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format).
sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With