How to do date calculation in drools?

风格不统一 提交于 2019-12-24 06:36:22

问题


I'm newly to drools and got a confusion on date comparison in drl files. I got an condition that to compare two Date type facts. The drl is like :

rule "TimeComparison"
    when
        $person:Person( date1 >= date2 )
    then
        //
end

Inside, date1 is three days after a known date. How to achieve the (Three days/weeks/months after a specific date) in drl rule files?


回答1:


Assuming your Date is java.util.Date, the < operator uses Date.before(date) and the > operator uses Date.after(date).

I suggest using Date.compareTo(), such as:

rule "TimeComparison"
    when
        $date
        $person:Person( date1.compareTo(date2) >= 0)
    then
        //
end

If date2 is not what you want for comparison, then substitute the desired for it inline, such as this for "date1 is after 'now'":

$person : Person(date1.compareTo(new Date()) >= 0)

Using java.time classes is much easier, such as with LocalDate:

$person : Person(date1.plusDays(3).compareTo(date2))

If the comparison date is a system "known", it may be desired to infer the calculated date as a new fact (here I simply made up the concept of a "PersonEffectiveDate") and use it where needed (change the approach/design/concept as needed for your situation):

rule "Determine person effective date"
    when
        $person : Person($date1 : date1)
    then
        // do the desired calculation
        Date $effectiveDate = $date1.plusDays(3);
        PersonEffectiveDate ped = new PersonEffectiveDate($person, $effectiveDate);
        insert(ped);
end

rule "TimeComparison"
    when
        PersonEffectiveDate($person : person, $effectiveDate : effectiveDate >= date2)
    then
        //
end

or something different, such as:

$person.date1.compareTo($effectiveDate) >= 0)


来源:https://stackoverflow.com/questions/40781259/how-to-do-date-calculation-in-drools

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!