Care use Date and Time class

xiaoxiao2021-03-06  45

The date and time class provided in Java, java.sql.date and java.sql.time will only read some values ​​from the database, which sometimes causes loss of data. For example, a field containing 2002/05/22 5:00:57 PM, which is obtained when the date is 2002/05/22, and the read time is 5:00:57 PM.

You need to understand the accuracy of the storage time in the database. Some databases, such as MySQL, accuracy of milliseconds, but other databases, including Oracle, when SQL Date type data, the data of millisecond is not saved. The BUG that is easy to discover in the following operations:

Get a date object in Java.

Read the date from the database

Trying to compare whether the two date objects are equal. If the millisecond is lost, two date objects that I think equal will be equally possible to return False.

Java.sql.TimeStamp class is higher than java.util.date class accuracy. This class contains a getTime () method, but it does not return data for additional precision portions, so a getnanos () method must be used. Numerical values ​​with femto seconds (i.e., additional precision portions) may be more than one milliseconds that do not have this part. If you know that the database you are using, you can use the value obtained by the following code:

Long time = timestamp.gettime () TimeStamp.getnanos () / 1000000;

The femto second part is why a java.sql.TimeStamp object is not equal to a java.util.date object, and a java.util.date object may be equal to a Java.SQL.TimeStamp object. This makes the Equals method should be kept alive.

The class associated with the time in the Java.sql package is important, but they may also lead to artificial errors.

This is because the complexity of these classes has been clearly described in Javadoc, but because these classes look simple and few people look at these documents.

转载请注明原文地址:https://www.9cbs.com/read-75366.html

New Post(0)