如何将时间从 java.util.Date 存储到 java.sql.Date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29392755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:55:24  来源:igfitidea点击:

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

javadate

提问by Deepak Verma

I want to convert java.util.Dateto java.sql.Datebut 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.Dateobject.

我想转换java.util.Date为,java.sql.Date但我也想要小时、分钟和秒,但 java.sql.Date 只能用于存储 date(no time) 。我尝试了下面的代码,但它只给出了java.sql.Date对象的年、月和日。

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

采纳答案by ericbn

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

java.sql.Date类型仅用于存储日期(无时间)信息,因为它映射到DATE不存储时间的 SQL类型。它的toString()方法的作用是:

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

以日期转义格式 yyyy-mm-dd 格式化日期。

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

要获得所需的输出,您可以使用java.sql.Timestamp,它存储日期时间信息,映射到 SQLTIMESTAMP类型。它的toString()方法输出您需要的内容:

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

以 JDBC 时间戳转义格式格式化时间戳:yyyy-mm-dd hh:mm:ss.ffffffffff,其中 ffffffffff 表示纳秒。

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"

回答by geekprogrammer

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

正如其他人所说,您需要使用 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

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