Arun Arun - 5 months ago 17x
SQL Question

Check 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 < ?, 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 (e.g. 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 ( {
            //code here