Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisted date in database not equal to retrieved date

I have a simple entity class that has a Date property. This property corresponds to a MySQL datetime column.

@Entity
public class Entity {

    @Column(name = "start_date")
    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Date startDate;

}

This is what an integration test I wrote looks like:

java.util.Date now = new java.util.Date();
Entity entity = new Entity();
entity.setStartDate(now);
entityService.save(entity); // save entity to database
entity = entityService.get(entity.getId()); // get entity back from database
Assert.assertEquals(entity.getStartDate(), now);

I would expect those two dates to be equal but they are not! Actually, I have :

now.getTime() = 1350160029831
entity.getStartDate().getTime() = 1350160029000

so there is a small gap between the two dates. I am really wondering where this gap could come from. It is not always the same and varies each time I start the testing process. In my database, the date stored is 2012-10-13 22:15:38.0.

Do I really need to clear milliseconds somewhere?

like image 805
Tunaki Avatar asked Oct 13 '12 20:10

Tunaki


1 Answers

From the MySQL documentation:

A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision. Although this fractional part is recognized, it is discarded from values stored into DATETIME or TIMESTAMP columns. For information about fractional seconds support in MySQL, see Section 11.1.5.6, “Fractional Seconds in Time Values”.

Note that you shouldn't use equals to compare dates anyway, because the various Date subclasses have buggy implementations, which cause problems such as a.equals(b) && !b.equals(a):

java.util.Date d1 = java.sql.Date.valueOf("2012-01-01");
java.util.Date d2 = new java.util.Date(d1.getTime());
java.util.Date d3 = new java.sql.Timestamp(d1.getTime());

System.out.println(d1.equals(d2)); // true
System.out.println(d2.equals(d1)); // true
System.out.println(d1.equals(d3)); // true
System.out.println(d3.equals(d1)); // false
System.out.println(d2.equals(d3)); // true
System.out.println(d3.equals(d2)); // false
like image 65
JB Nizet Avatar answered Oct 19 '22 06:10

JB Nizet