转载:http://spiritfrog.iteye.com/blog/324756
java.sql.Date,java.sql.Time和java.sql.Timestamp三个都是java.util.Date的子类(包装类)。他们跟java.util.Date有什么区别, 设计这三个类有什么用意呢?
先看看一个例子:
但是为什么java.sql.Date类型的值插入到数据库中Date字段中会发生数据截取呢?
java.sql.Date是为了配合SQL DATE而设置的数据类型。“规范化”的java.sql.Date只包含年月日信息,时分秒毫秒都会清零。格式类似:YYYY-MM-DD
当我们调用ResultSet的getDate()方法来获得返回值时,java程序会参照"规范"的java.sql.Date来格式化数据库中的数值。
可以看出,java.sql.Date,java.sql.Time和java.sql.Timestamp都是为了更好的规范化java.util.Date, 让它能更好的区分日期,时分秒。
一、java.util.Date向java.sql.Date的规范化
如果数据库中存在的非规范化部分的信息将会被劫取。在sun提供的ResultSet.java中这样对getDate进行注释的:
Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as a “java.sql.Date” object in the Java programming language.
同理。如果我们把一个java.sql.Date值通过PrepareStatement的setDate方法存入数据库时,java程序会对传入的java.sql.Date规范化
,非规范化的部分将会被劫取。
然而,我们java.sql.Date一般由java.util.Date转换过来,如:java.sql.Date sqlDate=new java.sql.Date(new java.util.Date().getTime()).
显然,这样转换过来的java.sql.Date丢失了日期部分.
在
http://www.thunderguy.com/semicolon/2003/08/14/java-sql-date-is-not-a-real-date/ 文章中提到,要保存java.util.Date的精确值,
我们需要利用java.sql.Timestamp.
java.sql.Date stores only date information, not times. Simply converting a
java.util.Date into a
java.sql.Date will silently set the time to midnight. So, to store date/times to be manipulated as
java.util.Date objects, don’t do this:
// BUG: loses time of day
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
do this instead:
preparedStatement.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
java.sql.Timestamp is not a date
* * *
二、java.sql.Timestamp到java.util.Date的转化
java.sql.Timestamp extends
java.util.Date , but it should not be used as a
Date . In JDK 1.3.1,
Timestamp.getTime() (inherited from
Date ) returns the time to the nearest second only, but JDK 1.4.2 and JDK 1.5 it returns the time to the nearest millisecond as expected. So in JDK 1.3, when reading a timestamp from a
ResultSet , don’t do this:
// Java 1.3
java.util.Date d = resultSet.getTimestamp(1);
long millis = d.getTime(); // BUG: loses fractional seconds in JDK 1.3
To get the full date including milliseconds, you have to do this:
java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
java.util.Date d = new java.util.Date(timestamp.getTime() +
timestamp.getNanos() / 1000000);
//nanos是纳秒,1纳秒=百万分之一毫秒
In JDK 1.4.2 and JDK 1.5, you can just do this, depending on what you’re going to do with the Date:
// Java 1.4+
java.util.Date d = resultSet.getTimestamp(1);
But this might be safer since it avoids any other potential
Timestamp problems:
// Java 1.4+
java.util.Date d = new java.util.Date(resultSet.getTimestamp(1).getTime());
If your code needs to run on JDK 1.3 and later, you’ll have to do this:
java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
long millis = (timestamp.getTime() / 1000) * 1000 + timestamp.getNanos() / 1000000;
java.util.Date d = new java.util.Date(millis);