使用Groovy将日期增加到第二天

时间:2017-12-18 13:08:45

标签: datetime groovy soapui datetime-format

尝试将1天添加到简单日期格式。

import java.text.SimpleDateFormat 
Date date = new Date();
def dateformat =  new SimpleDateFormat("YYYY-MM-dd")
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate

Date date1 = (Date)dateformat.parse(currentDate);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1); 
log info c1.add(Calendar.Date,1);

行中出错:

  

“log info c1.add(Calendar.Date,1);”   groovy.lang.MissingPropertyException:没有这样的属性:类的信息:第16行的错误:

注意:当前日期应该是将来的任何日期,我想增加1天。

2 个答案:

答案 0 :(得分:1)

嗯,您提供的错误清楚地告诉您,您有语法错误。它说没有财产info

这是因为你写了

log info c1.add(Calendar.Date,1);

而不是

log.info c1.add(Calendar.Date,1);

如果您使用了正确的语法,则会抱怨Calendar没有属性Date

所以而不是

c1.add(Calendar.Date, 1)

你的意思

c1.add(Calendar.DAY_OF_MONTH, 1)

但是在Groovy中,您甚至可以使用

更轻松
c1 = c1.next()

答案 1 :(得分:1)

您可以使用TimeCategory添加一天,如下所示:

use(groovy.time.TimeCategory) {
  def tomorrow = new Date() + 1.day
  log.info tomorrow.format('yyyy-MM-dd')
}

编辑:基于OP评论

这是另一个动态添加方法,即nextDay()Date类。

//Define the date format expected
def dateFormat = 'yyyy-MM-dd'

Date.metaClass.nextDay = {
   use(groovy.time.TimeCategory) {
      def nDay = delegate + 1.day
      nDay.format(dateFormat)
   }
}

//For any date
def dateString = '2017-12-14'
def date = Date.parse(dateFormat, dateString)
log.info date.nextDay()


//For current date
def date2 = new Date()
log.info date2.nextDay()

您可以快速在线 demo

相关问题