gpt4 book ai didi

java - 获取 hibernate 中日期范围内的所有日期值

转载 作者:行者123 更新时间:2023-12-01 15:34:57 26 4
gpt4 key购买 nike

我需要知道如何获取 Hibernate 查询结果集中某个日期范围内的所有日期。

它应该类似于下面的 SQL 伪代码

Select "ALL DATES" from ???? where date between TO_DATE('date-val','format') and TO_DATE('date-val','format').

它可能需要一些不同的逻辑,但如果我给出一个范围,如 2011 年 2 月 5 日到 2011 年 3 月 2 日它应该返回结果集中该范围内的所有日期...即

resultset = 5-Feb-2011, 6-Feb-2011,..... 28-Feb-2011, 1-March-2011, 2-March-2011


更新:以下查询在 Oracle 中给出了所需的结果集

select 
d.dateInRange as dateval,
eventdesc,
nvl(td.dist_ucnt, 0) as dist_ucnt
from (
select
to_date('03-NOV-2011','dd-mon-yyyy') + rownum - 1 as dateInRange
from all_objects
where rownum <= to_date('31-DEC-2011','dd-mon-yyyy') - to_date('03-NOV-2011','dd-mon-yyyy') + 1
) d
left join (
select
currentdate,
count(distinct(grauser_id)) as dist_ucnt,
eventdesc
from
txn_summ_dec

group by currentdate, eventdesc
) td on td.currentdate = d.dateInRange order by d.dateInRange asc

Resultset:
Date eventdesc dist_cnt
2011-11-03 00:00:00 null 0
and so on..
2011-11-30 00:00:00 null 0
2011-12-01 00:00:00 Save Object 182
....
2011-12-31 00:00:00 null 0

最佳答案

这个逻辑应该负责生成范围:

public static List<Date> dayRange(Date begin, Date end) {
if (end.before(begin)) {
throw new IllegalArgumentException("Invalid range");
}

final List<Date> range = new ArrayList<>();
final Calendar c1 = extractDate(begin);
final Calendar c2 = extractDate(end);

while (c1.before(c2)) {
range.add(c1.getTime()); // begin inclusive
c1.add(Calendar.DATE, 1);
}
range.add(c2.getTime()); // end inclusive

return range;
}

private static Calendar extractDate(Date date) {
final Calendar c = Calendar.getInstance();

c.setTime(date);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

return c;
}

不像 Joda Time 那样漂亮和简洁,但可以让你继续前进。

如果您需要的只是显示没有结果的日期的查询结果为零,请运行按日期分组的原始查询(不带左连接),然后填写缺失的日期。假设您的查询返回 Map<String, Long> :

final DateFormat df = new SimpleDateFormat("d-MMM-yyyy", Locale.US);

final Date begin = df.parse("5-Feb-2011");
final Date end = df.parse("2-March-2011");

final List<Date> range = dayRange(begin, end);
final Map<String, Long> result = // code to execute your query

for (Date date: range) {
String key = df.format(date);
if(!result.containsKey(key)) {
result.put(key, 0l);
}
}

我希望这会有所帮助。

关于java - 获取 hibernate 中日期范围内的所有日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012224/

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