java - 为java SQL Date添加小时,分钟和秒

标签 java mysql

我在使用 Java 计算数据库中的值时遇到了一些问题。

我正在尝试从我的数据库中按日期计算一些值,但它们有小时、分钟和秒。如果我使用 java.sql.Date 进行搜索,它只允许我输入年、月和日,因此带有日期的值:year"-"month"-31(小时:minutes:seconds != 00:00:00)" 不会被计算在内。

有没有办法将小时、分钟和秒添加到 java.sql.Date 中?如果不是,那么更好的方法是什么?

我的代码:

public static int getAmountPos(Connection con, Integer month, Integer year) {

        java.sql.Date date1 = java.sql.Date.valueOf(year+"-"+month+"-01");
        java.sql.Date date2 = java.sql.Date.valueOf(year+"-"+month+"-31");

        Integer amount = null;
        String sql = "SELECT COUNT(*) AS 'cantidad' "
                + " FROM table.point_of_service "
                + " WHERE registration_date between ? AND ?";

        PreparedStatement ps = con.getPreparedStatement(sql);
        ps.setDate(1, date1);
        ps.setDate(2, date2);

        ResultSet rs = ps.executeQuery();

        if(rs.next()) {
            amount = rs.getInt("cantidad");
        }

        return amount;
    }

最佳答案

java.sql.Date 类不用于保存有关时间的信息。它只包含日期(年、月、日)。您应该根据需要使用 java.sql.Timestamp

关于java - 为java SQL Date添加小时,分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35438521/

相关文章:

java - 轴2 + Tomcat : Web service working directory

java - iTextPDF : Set page size of PDF according to the size of the image to be inserted

java - 在 headless (headless)环境中获取键盘事件

MySQL select SUM with conditional to change the sign of column being summed

mysql - 如何在 MySQL 中以 Ruby 哈希存储多封电子邮件?

java - Eclipse,删除覆盖错误

java - Spring Security @PreAuthorize 使用 SpEL 语言访问 Autowiring bean

html - 如何从sql文本字段中获取带有html标签的 "grep"行?

mysql - 可以使用十六进制作为数据库 ID 吗?

Python打印SQL语句结果