数据库中的保留日期不等于检索日期 [英] Persisted date in database not equal to retrieved date

查看:173
本文介绍了数据库中的保留日期不等于检索日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有Date属性的简单实体类.此属性对应于MySQL datetime列.

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

所以两个日期之间有一个很小的差距.我真的很想知道这种差距可能从何而来.它并不总是相同的,并且每次我开始测试过程时都会有所不同. 在我的数据库中,存储的日期是2012-10-13 22:15:38.0.

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?

推荐答案

来自

DATETIME或TIMESTAMP值可以包含尾随小数 秒部分的精度最高为微秒(6位数).虽然这个 识别小数部分,将其从存储到 DATETIME或TIMESTAMP列.有关分数的信息 MySQL中的秒支持,请参见第11.1.5.6节 时间值".

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".

请注意,您无论如何都不应该使用equals来比较日期,因为各种Date子类具有错误的实现,这会引起诸如a.equals(b) && !b.equals(a):

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

这篇关于数据库中的保留日期不等于检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆