首页 > 解决方案 > 给定 2 LocalDateTime 基于天或天/小时生成过滤器

问题描述

我想要一个给定时间间隔粒度(例如 DAY、HOUR 等)并且 2 LocalDateTime ab生成以下类型的字符串的方法:

让我们假设a = '2018-01-01 12:23:23'b = '2018-01-10 15:18:13'如果给定的时间间隔是

现在,我只需要这两种情况,但我想灵活一点(假设我想在未来用分钟做同样的事情)

我找不到这样做的聪明方法,例如在 Java 中使用 Duration 类,但我只能硬编码上述两个粒度的结果

标签: javadatetimetimestamptimestamp-with-timezonelocaldate

解决方案


为什么你认为使用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)

推荐阅读