Exercise caution when using the Date and Time classes

Source: Internet
Author: User

 

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.