Java. SQL. Date and java. SQL. Time in AVA only read a certain value from the database, which sometimes leads to data loss. For example, for a field containing 5:00:57, the read date is, And the read time is 5:00:57.
You need to know the storage time precision in the database. Some databases, such as MySQL, have a precision of milliseconds. However, some databases, including Oracle, do not save data in milliseconds when storing SQL DATE data. The following operations are prone to bugs that are not easily discovered:
Get a date object in JAVA.
Read date from database
Try to compare whether two date objects are equal. If the millisecond part is lost, the Equals method may return false for two date objects that are originally considered equal.
Java. SQL. Timestamp is more accurate than java. util. Date. This class contains a getTime () method, but it does not return data with extra precision. Therefore, you must use the getNanos () method. A value with a microsecond (I .e. an extra precision) may be one millisecond larger than a value without this part. If you know that the database you are using is saved in milliseconds, you can use the following code to obtain the value:
Long time = timestamp. getTime () + timestamp. getNanos ()/1000000;
The microsecond part is why a java. SQL. the Timestamp object is not equal to a java. util. date object, while a java. util. the Date object may be equal to a java. SQL. the reason for the Timestamp object. This breaks the symmetry that the equals method should maintain.
It is important to use time-related classes in the java. SQL package, but they may also cause human errors.
This is because although the complexity of these classes has been clearly described in javadoc, these classes seem very simple and few people have read these documents.