gpt4 book ai didi

java - 如何在 hibernate 中比较日期

转载 作者:IT老高 更新时间:2023-10-28 13:52:31 26 4
gpt4 key购买 nike

在我的数据库中,日期为 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04 -08 04:04:51 等,我需要在日期字段中检索当前日期的数据。我的意思是我只需要匹配 2012-04-09' 。我如何使用 hibernate 条件来做到这一点。

最佳答案

使用 Restrictions.between()生成日期列在 '2012-04-09 00:00:00' 和 '2012-04-09 23:59:59' 之间的 where 子句

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");

criteria.add(Restrictions.between("dateField", fromDate, toDate));

请注意,Criteria API 中使用的所有属性都是 Java 属性名,而不是实际的列名。


更新:仅使用 JDK 获取当前日期的 fromDate 和 toDate

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();

calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();

criteria.add(Restrictions.between("dateField", fromDate, toDate));

关于java - 如何在 hibernate 中比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com