如何将java.util.Date转换为java.sql.Date [英] How to convert java.util.Date to java.sql.Date
问题描述
我想将 java.util.Date
转换为 java.sql.Date
,但我想要几分钟,以及秒。我尝试了下面的代码,但它只给了$ code> java.sql.Date 对象的年,月和日。
I want to convert java.util.Date
to java.sql.Date
but I want hours, minutes, and seconds as well. 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);
当前输出:
2011-02-10
期望的输出:
2011-02-10 12:05:34
推荐答案
java.sql.Date
类型用于仅存储日期(无时间)信息,因为它映射到SQL DATE
类型,不存储时间。它的 toString()
方法是:
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:
格式化日期转义格式yyyy -mm-dd。
Formats a date in the date escape format yyyy-mm-dd.
要实现所需的输出,您可以使用 java.sql.Timestamp
,其中存储日期和时间信息,映射到SQL TIMESTAMP
类型。其 toString()
方法输出您需要的内容:
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:
在JDBC时间戳转义格式中格式化时间戳:yyyy-mm-dd hh:mm:ss.fffffffff,其中ffffffffff表示纳秒。
Formats a timestamp in JDBC timestamp escape format: yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds.
示例:
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"
这篇关于如何将java.util.Date转换为java.sql.Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!