如何将时间从java.util.Date存储到java.sql.Date中 [英] How to store time from java.util.Date into java.sql.Date

查看:339
本文介绍了如何将时间从java.util.Date存储到java.sql.Date中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 java.util.Date 转换为 java.sql.Date 但我想要几小时,分钟,以及秒,但java.sql.Date只能用于存储日期(没有时间)。我尝试了下面的代码,但它只给出了 java.sql.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);

当前输出:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆