Search code examples
apache-nifi

NiFi How to Add Months to a Date


I know one can add milliseconds to a date for adding days or weeks:

https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html#now

But since months' lengths are different, that will not work. How can I add 6 months to the now() function of NiFi?


Solution

  • After needing this time and again, I just decided to do it the workaround way without using external scripts which potentially break with upgrades and adds complexity. The below deducts one month.

    Set the original date to work from.

    use below for testing dates:

    ${literal('2022-01'):toDate('yyyy-MM')} #202112
    ${literal('2022-09'):toDate('yyyy-MM')} #202208
    ${literal('2022-11'):toDate('yyyy-MM')} #202210
    

    Split out vars

    Determine new vars

    ${this_month:equals("1"):ifElse("12",${this_month:minus(1)})}
    ${this_month:equals("1"):ifElse(${this_year:minus(1)},${this_year})}
    

    Set new date

    ${new_year:append(${new_month:padLeft(2,"0")})}
    

    Hope this helps someone somewhere out there.