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

date, java, jdbc, sql, sql-server

Solution

You are comparing `Date` and `long`

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()){

    }

Problem

i am curious why the if comparison is giving false: 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. I Appreciate any help to understand this behavior.

Original source