简体   繁体   中英

Check java.util.date and MySql timestamp belong to same day

From Java, I have a Date object and how should I compare it with the Mysql timestamp to check whether it belongs to the same day?

select c.content, c.contentDate from Contents c where c.contentDate = ?1 and c.userName = ?2

The above sql should return records that belong to a particular day(Date). But, how to compare the Java Date and Sql Timestamp?

If contentDate can be 2 AM or 9 PM of the given day, then you cannot use contentDate = ? , because there is no single value for a whole day. You need to say contentDate >= ? and contentDate < ? contentDate >= ? and contentDate < ? , where the first ? is midnight at the beginning of the day, and the second ? is midnight at the beginning of the following day. You calculate those two values in Java (eg using Calendar or LocalDate ), then use setDate() on the PreparedStatement to set the values.

LocalDate easter = LocalDate.of(2016, Month.MARCH, 27);

// Get all content from Easter Day (Mar 27, 2016)
String sql = "SELECT * FROM Contents WHERE contentDate >= ? and contentDate < ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setDate(1, java.sql.Date.valueOf(easter));
    stmt.setDate(2, java.sql.Date.valueOf(easter.plusDays(1)));
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            //code here
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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