简体   繁体   English

比较java中的两个日期类型变量

[英]compare two date types variable in java

I found some problem in compare two data types Variable -> java.sql.Date type.我在比较两种数据类型 Variable -> java.sql.Date 类型时发现了一些问题。

Firstly i'm createing current data (yyyy-mm-dd):首先,我正在创建当前数据(yyyy-mm-dd):

java.util.Date date = new java.util.Date();

java.sql.Date dateSql = new Date(date.getTime());

Secoundly, im receiving data from MySQL:其次,我从 MySQL 接收数据:

MyDataEntity myDataEntity = session.getNamedQuery(MyDataEntity.GET_ELEMENT).uniqueResult();

Then i'm trying to compare two dates:然后我试图比较两个日期:

if(dataSql != myDataEntity.getDate()){
System.out.println("different");
}else{
System.out.println("these same");
}

And the effect is, that always these two dates are different.结果是,这两个日期总是不同的。 But when i'm printing values of these two datas, i've got these same values:但是当我打印这两个数据的值时,我得到了这些相同的值:

System.out.println(dataSql);
System.out.println(myDataEntity.getDate);

Effect:影响:

2012-11-16
2012-11-16

But, i found one issue:但是,我发现了一个问题:

if i make:如果我做:

long date1 = dateSql.getTime();  // print 1353106800000
long date2 = myDataEntity.getDate().getTime(); // print 1353234605091

So how to compare two dates (yyyy-mm-dd) ?那么如何比较两个日期 (yyyy-mm-dd) 呢?

First, use .equals(..) to compare non-primitive objects - someDate.equals(anotherDate)首先,使用.equals(..)来比较非原始对象 - someDate.equals(anotherDate)

Using == compares their jvm identities - ie if they are the same object on the heap, rather than their value.使用==比较它们的 jvm 身份 - 即它们是否是堆上的相同对象,而不是它们的值。

Then make sure you compare the right things - you want equal dates, then you should discard the hours, minutes and days.然后确保你比较正确的东西——你想要相等的日期,然后你应该放弃小时、分钟和天数。 For that you can use:为此,您可以使用:

  • math to subtract the millis数学减去毫秒
  • java.util.Calendar 's .set(..) methods. java.util.Calendar.set(..)方法。
  • joda-time DateMidnight - best option joda-time DateMidnight - 最佳选择

This is a well-known issue: java.sql.Date objects remove the precision found at the lower end of the date object (see all those zeroes at the end of your print).这是一个众所周知的问题:java.sql.Date 对象删除了日期对象下端的精度(查看打印末尾的所有零)。 So you must normalise the precision between your java.util.Date and java.sql.Date.因此,您必须标准化 java.util.Date 和 java.sql.Date 之间的精度。

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Oh, and use .equals to compare objects, not ==.哦,使用 .equals 来比较对象,而不是 ==。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM