java - 给定 2 LocalDateTime 基于天或天/小时生成过滤器
问题描述
我想要一个给定时间间隔粒度(例如 DAY、HOUR 等)并且 2 LocalDateTime a和b生成以下类型的字符串的方法:
让我们假设a = '2018-01-01 12:23:23'
,b = '2018-01-10 15:18:13'
如果给定的时间间隔是
- DAY:a 和 b 舍入为天,输出为字符串
"d >= '2018-01-01' and d <= '2018-01-10"
- HOUR => 这里的粒度是小时,所以 a 和 b 舍入到小时,字符串将是
"(d == '2018-01-01' and h >= 12) or (d >= '2018-01-02' and d <= '2018-01-09') or (d == '2018-01-10 and h <= 15)"
现在,我只需要这两种情况,但我想灵活一点(假设我想在未来用分钟做同样的事情)
我找不到这样做的聪明方法,例如在 Java 中使用 Duration 类,但我只能硬编码上述两个粒度的结果
解决方案
为什么你认为使用Duration
它会是一种“聪明的方式”?它不是。您的两个LocalDateTime
对象具有构建文本结果所需的所有值。
例子:
public enum Granularity { DAY, HOUR }
public static String toSqlCondition(LocalDateTime min, LocalDateTime max, Granularity granularity) {
switch (granularity) {
case DAY:
return "d >= '" + min.toLocalDate() + "' and d <= '" + max.toLocalDate() + "'";
case HOUR:
return "(d == '" + min.toLocalDate() + "' and h >= " + min.getHour() + ") or " +
"(d >= '" + min.toLocalDate().plusDays(1) + "' and d <= '" + max.toLocalDate().minusDays(1) + "') or " +
"(d == '" + max.toLocalDate() + "' and h <= " + max.getHour() + ")";
default:
throw new UnsupportedOperationException("Cannot build SQL condition with granularity " + granularity);
}
}
测试
LocalDateTime a = LocalDateTime.parse("2018-01-01T12:23:23");
LocalDateTime b = LocalDateTime.parse("2018-01-10T15:18:13");
System.out.println(toSqlCondition(a, b, Granularity.DAY));
System.out.println(toSqlCondition(a, b, Granularity.HOUR));
输出
d >= '2018-01-01' and d <= '2018-01-10'
(d == '2018-01-01' and h >= 12) or (d >= '2018-01-02' and d <= '2018-01-09') or (d == '2018-01-10' and h <= 15)
推荐阅读
- python - 如果在列表中找到关键字
- apache-spark - 使用服务帐号和 IAM 角色管理 dataproc 集群访问
- python - 全局变量说它没有在函数中定义
- ios - 无法使用 JSONDecoder 从 rawg.io 检索 API 结果
- flutter - 如何在 listview builder 上为每个块打开不同的 URL?
- python - 欧拉近似
- javascript - 如何在javascript中访问函数之外的数组
- typescript - 为什么不能使用“type A = Promise
" 作为异步函数的返回类型? - asp.net - 我们如何触发 Azure Notification Hub 从 .net Web 应用程序向 iOS 设备发送推送通知?
- javascript - 有没有办法让共享条件应用于复制的工作表?