给定2 LocalDateTime会根据天或天/小时生成过滤器

时间:2018-10-31 22:42:31

标签: java datetime timestamp timestamp-with-timezone localdate

我想有一个给定时间间隔粒度(例如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类,但是我只是能够对上述两种粒度的结果进行硬编码

1 个答案:

答案 0 :(得分:1)

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