在groovy中向日期添加月份不起作用

在groovy中向日期添加月份不起作用,groovy,timecategory,Groovy,Timecategory,在下面的代码中,只有年份被添加到我的日期。月份没有增加 def calculateLicense(Date bd, int yr, int mon=0){ use (groovy.time.TimeCategory) { Date licenseDate = bd + yr.years + mon.months println "License date:" + licenseDate.format('mm/dd/yyyy') } 您在此处使用的

在下面的代码中,只有年份被添加到我的日期。月份没有增加

def calculateLicense(Date bd, int yr, int mon=0){
    use (groovy.time.TimeCategory) {
        Date licenseDate = bd + yr.years + mon.months
        println "License date:" + licenseDate.format('mm/dd/yyyy')
    }

您在此处使用的格式:

licenseDate.format('mm/dd/yyyy')
表示
(小时分钟)/(月日)/(年)
。应该是

licenseDate.format('MM/dd/yyyy')
相反,因为
MM
代表一年中的月份。您负责添加年和月的代码是正确的,您只遗漏了格式设置和以正确格式显示日期

请看下面的示例:

import groovy.time.TimeCategory

def calculateLicense(Date bd, int yr, int mon = 0) {
  use(TimeCategory) {
    Date licenseDate = bd + yr.years + mon.months
    println "License date:" + licenseDate.format('MM/dd/yyyy')
  }
}

calculateLicense(Date.parse("yyyy-MM-dd", "2018-06-06"), 2, 3)
calculateLicense(Date.parse("yyyy-MM-dd", "2018-06-06"), 2)
输出:

License date:09/06/2020
License date:06/06/2020

只是想问一下:您的默认值是addin 0 month。您不只是遇到这种情况吗?yr=Integer.parseInt(sc.nextLine())如果(choice==2){println“输入到期月份:”mon=Integer.parseInt(sc.nextLine())calculateLicense(bd,yr,mon)}否则{calculateLicense(bd,yr)}我遇到两种情况,如果我不传递mon参数,它默认为“0”