计算JPA中两个日期之间的天数 [英] Count number of days between 2 dates in JPA

查看:647
本文介绍了计算JPA中两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算JPA中两个日期之间的天数.

I need to count the number of days between 2 dates in JPA.

例如:

CriteriaBuilder.construct(
  MyCustomBean.class
  myBean.get(MyBean_.beginDate), //Expression<Date>
  myBean.get(MyBean_.endDate), //Expression<Date>
  myDiffExpr(myBean) //How to write this expression from the 2 Expression<Date>?
);

到目前为止,我尝试了:

So far, I tried :

1)CriteriaBuilder.diff().但不会编译,因为此方法需要N extends NumberDate不扩展Number.

1) CriteriaBuilder.diff(). but it does not compile because this method expects some N extends Number and the Date does not extend Number.

2)我试图扩展PostgreSQL82Dialect(因为我的目标数据库是PostgreSQL):

2) I tried to extend the PostgreSQL82Dialect (as my target database is PostgreSQL) :

public class MyDialect extends PostgreSQL82Dialect {

  public MyDialect() {
    super();
    registerFunction("datediff", 
    //In PostgreSQL, date2 - date1 returns the number of days between them.
    new SQLFunctionTemplate(StandardBasicTypes.LONG, " (?2 - ?1) "));
  }
}

这将编译并且请求成功,但是返回的结果不一致(今天和明天之间为78天).

This compiles and the request succeeds but the returned result is not consistent (78 days between today and tomorrow).

您将如何做?

推荐答案

我终于发现问题出在以下事实:参数的顺序不是我期望的顺序:

I finally found that the problem comes from the fact that the order of the parameters is not the one I expected :

/*
 *(?2 - ?1) is actually equivalent to (? - ?).
 * Hence, when I expect it to evaluate (date2 - date1), 
 * it will actually be evaluated to (date1 - date2)
 */
new SQLFunctionTemplate(StandardBasicTypes.LONG, " (?2 - ?1) "));

我打开了新问题为了知道此行为是错误还是功能:

I opened a new question in order to know if this behavior is a bug or a feature :

这篇关于计算JPA中两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆