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

后端 未结 2 630
萌比男神i
萌比男神i 2021-01-05 01:32

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(n

相关标签:
2条回答
  • 2021-01-05 02:03

    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

    0 讨论(0)
  • 2021-01-05 02:04

    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"
    
    0 讨论(0)
提交回复
热议问题