Subtract months from date in velocity

荒凉一梦 提交于 2021-02-08 11:01:41

问题


I am trying to get the date a certain number of months ago from a given date

I've tried converting to Calendar to then use the add method, but that didn't work:

#set( $myCalendar =  $date.toCalendar($endDate))
#set( $startdate = $calendarstart.add("MONTH", -$minusMonths))

I've tried to do this in a few different ways:

#set( $temp =  0 - $numberOfMissedPremiums)
#evaluate($calendarstart.add( 2 , $temp ))
#set( $a = $calendarstart.add( 2 , $temp ))

I've even tried defining blocks, but that didn't work either


回答1:


The Calendar.add() method takes an int, not a string, for the field indicator. To change the months, you need the Calendar.MONTH method, which is 2.

So you would write:

#set( $startdate = $calendarstart.clone() )
$startdate.add(2, -$minusMonths)

Also, if you're still using Velocity 1.7, you may need to write:

#set( $startdate = $calendarstart.clone() )
#set( $temp = 0 - $minusMonths )
$startdate.add(2, $temp)

To nicify a bit this code, you can use the FieldTool, which you can configure like this:

<tools>
  <toolbox scope="application">
    <tool key = "cal"
          class="org.apache.velocity.tools.generic.FieldTool"
          include="java.util.Date"/>
  </toolbox>
</tools>

So you can now write:

#set( $startdate = $calendarstart.clone() )
$startdate = $calendarstart.add($cal.MONTH, -$minusMonths)

(and I let you adapt the 1.7 version).

As a final note, please take a moment to consider moving this code to a Java tool. VTL is a template language, and what you are trying to do seems more like a business logic task.

(Edited) As noted in @luis-rico first comment, Calendar.add() returns void. Calendar is a mutable object, so if you want to keep the original Calendar instance, you will have to clone it first. Then you can directly call $startdate.add(2, -$minusMonth) in the template, since void results aren't printed.




回答2:


OK, so I finally managed to get it working:

#set( $minusmonths =  $math.mul($numberOfMonthsToSubtract,-1))    
#set( $Mycalendar = $date.getCalendar())   
#set( $Dateformat = "yyyy-MM-dd" )
$Mycalendar.setTime($convert.parseDate(
    $endDate, 
    $Dateformat
  ))
#set( $calConst = $field.in($Mycalendar) )
$Mycalendar.add($calConst.MONTH, $minusmonths.intValue())

The problem seemed to be on the Calendar.add() not parsing the value correctly, it only accepts Int and was receiving a Number.

The way I defined the calendar variable was giving some problems as well.



来源:https://stackoverflow.com/questions/56734839/subtract-months-from-date-in-velocity

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