我想有一个给定时间间隔粒度(例如DAY,HOUR等)的方法,并且2 LocalDateTime a 和 b 生成一个字符串以下类型:
假设给定的时间间隔为a = '2018-01-01 12:23:23'
和b = '2018-01-10 15:18:13'
"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)"
现在,我只需要这两种情况,但是我想保持灵活性(假设我希望将来几分钟内做同样的事情)
我找不到一种明智的方法,例如在Java中使用Duration类,但是我只是能够对上述两种粒度的结果进行硬编码
答案 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)