JDBC java.sql.Date() 比较给出错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24790436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:51:07  来源:igfitidea点击:

JDBC java.sql.Date() comparison is giving false

javasqlsql-serverdatejdbc

提问by Israelm

i am curious why the if comparison is giving false:

我很好奇为什么 if 比较给出错误:

I am inserting a date into a date field using this code:

我正在使用以下代码将日期插入日期字段:

preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
System.out.println("sql date" + new java.sql.Date(new java.util.Date().getTime()));
output is: 2014-07-16

After the insertion i query the database to find out if records has been inserted today:

插入后,我查询数据库以查明今天是否插入了记录:

    String sql = select MAX (last_modified) as last_modified from mydb.mytable
    ResultSet rs = stmt.executeQuery(sql);

    while (rs.next())
    {

        if (rs.getDate(1).equals(new java.sql.Date(new java.util.Date().getTime())))
        {
            System.out.println("Same Date in here not need to update");
         }
        else
        {
            System.out.println("Dates are different");
        }

        System.out.println("date from db: " + rs.getDate(1));  
        System.out.println("new sql date: " + new java.sql.Date(new java.util.Date().getTime()));: 
    }

The output is:

输出是:

Dates are different
date from db: 2014-07-16
new sql date: 2014-07-16

I think both dates are similar and both are casting to match java.sql.Date, maybe the condition is not correct.

我认为两个日期都相似,并且都在转换以匹配 java.sql.Date,也许条件不正确。

I Appreciate any help to understand this behavior.

我感谢任何帮助理解这种行为。

采纳答案by Jigar Joshi

You are comparing Dateand long

你在比较Datelong

if (rs.getDate(1).equals(new java.sql.Date(new java.util.Date().getTime())))

change it to

将其更改为

if (rs.getDate(1).getTime() == System.currentTimeInMillis())

from your commment you want day level precision so

根据您的评论,您需要日级精度,所以

    Calendar startOfToday = Calendar.getInstance();
    Calendar endOfToday = Calendar.getInstance();
    endOfToday.setTime(startOfToday.getTime());

    startOfToday.set(Calendar.HOUR_OF_DAY, 0);
    startOfToday.set(Calendar.MINUTE, 0);
    startOfToday.set(Calendar.SECOND, 0);
    startOfToday.set(Calendar.MILLISECOND, 0);

    endOfToday.set(Calendar.HOUR_OF_DAY, 23);
    endOfToday.set(Calendar.MINUTE, 59);
    endOfToday.set(Calendar.SECOND, 59);
    endOfToday.set(Calendar.MILLISECOND, 999);

    long transactionDate = rc.getDate(1).getTime();
    if(transactionDate >= startOfToday.getTimeInMillis() && transactionDate <= endOfToday.getTimeInMillis()){

    }

回答by Bohemian

Change your test to:

将您的测试更改为:

if (rs.getDate(1).toString().equals(new java.sql.Date(System.currentMillis()).toString())

回答by Basil Bourque

You are working too hard. There are easier and clearer ways to do such comparisons in modern Java.

你工作太辛苦了。在现代 Java 中有更简单、更清晰的方法来进行此类比较。

The old java.util.Date, java.sql.Date, and .Calendar classes are notoriously troublesome and should be avoided.

旧的 java.util.Date、java.sql.Date 和 .Calendar 类是出了名的麻烦,应该避免使用。

java.sql.Dateis a Hack

java.sql.Date是一个黑客

A java.sql.Date is merely a java.util.Date with its time-of-day set to 00:00:00 (UTC). This is an old lame hack to get around the fact that early versions of Java lacked a class to represent a date-only without any time-of-day or time zone.

java.sql.Date 只是一个 java.util.Date ,其时间设置为 00:00:00 (UTC)。这是一个古老的蹩脚黑客,以解决早期版本的 Java 缺少一个类来表示没有任何时间或时区的仅日期的事实。

java.time

时间

Now Java 8 does have a date-only class, LocalDate, found in the new java.time package.

现在 Java 8 确实有一个仅限日期的类LocalDate,可以在新的java.time 包中找到

Methods have been added to the java.sql.Dateclass to convert to/from LocalDate.

java.sql.Date类中添加了与 LocalDate 相互转换的方法。

LocalDate localDate = someSqlDate.toLocalDate();
LocalDate today = LocalDate.now( ZoneOffset.UTC ); // Pass a time zone to get current date in UTC for fair comparison.
boolean localDateIsToday = localDate.isEqual( today );

Going the other way…

走另一条路……

java.sql.Date sqlDate = java.sql.Date.valueOf( someLocalDate );

Table of date-time types in Java (both legacy and modern) and in standard SQL

Java(旧版和现代版)和标准 SQL 中的日期时间类型表

JDBC 4.2 Driver

JDBC 4.2 驱动程序

If your JDBC driverhas been updated to support JDBC 4.2, then according to the JDBC 4.2 Spec Update(item # 21) you can call the getObjectmethod on a ResultSetto directly obtain a LocalDateobject.

如果您的JDBC 驱动程序已更新为支持JDBC 4.2,那么根据JDBC 4.2 规范更新(第 21 项)您可以调用 a 上的getObject方法ResultSet来直接获取LocalDate对象。

LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;

Likewise, call PreparedStatement::setObjectto pass a LocalDateobject to a SQL DATE typecolumn in your database.

同样,调用PreparedStatement::setObjectLocalDate对象传递给数据库中的SQL DATE 类型列。

myPreparedStatement.setObject( … , localDate ) ;

Avoid java.sql.Datealtogether.

java.sql.Date完全避免。

Joda-Time

乔达时间

The java.time package was inspired by the Joda-Timelibrary. You can use it in earlier versions of Java where java.time is not available. Joda-Time too offers a LocalDateclass.

java.time 包的灵感来自Joda-Time库。您可以在 java.time 不可用的早期 Java 版本中使用它。Joda-Time 也提供了一个LocalDate课程。