减去日期中的月份速度 [英] Subtract months from date in velocity

查看:72
本文介绍了减去日期中的月份速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从给定日期获取几个月前的日期

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

我尝试过转换为日历,然后使用add方法,但这没用:

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

推荐答案

Calendar.add()方法采用int而非字符串作为字段指示符.要更改月份,您需要使用Calendar.MONTH方法,即2.

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.

所以你会写:

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

此外,如果您仍在使用Velocity 1.7,则可能需要编写:

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)

要对此代码稍加修饰,可以使用 FieldTool ,您可以这样配置:

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>

所以您现在可以写:

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

(我让您采用1.7版本).

(and I let you adapt the 1.7 version).

最后,请花点时间考虑将这段代码移至Java工具.VTL是一种模板语言,您尝试执行的操作似乎更像是业务逻辑任务.

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.

(已编辑)如@ luis-rico的第一条注释所述, Calendar.add()返回void.Calendar是一个 mutable 对象,因此,如果要保留原始Calendar实例,则必须先对其进行克隆.然后,您可以直接在模板中调用 $ startdate.add(2,-$ minusMonth),因为不会打印出无效结果.

(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.

这篇关于减去日期中的月份速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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