使用 Groovy 将日期增加到第二天
Increment date to the next day using Groovy
正在尝试向简单日期格式添加 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:No such property: info for class: Script16 error at line: 10
注意:当前日期应该是未来的任何日期,我想增加 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()
您可以使用TimeCategory
添加天,如下所示:
use(groovy.time.TimeCategory) {
def tomorrow = new Date() + 1.day
log.info tomorrow.format('yyyy-MM-dd')
}
编辑:基于 OP 评论
还有一个方法是动态添加方法,比如nextDay()
到Date
class.
//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
正在尝试向简单日期格式添加 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:No such property: info for class: Script16 error at line: 10
注意:当前日期应该是未来的任何日期,我想增加 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()
您可以使用TimeCategory
添加天,如下所示:
use(groovy.time.TimeCategory) {
def tomorrow = new Date() + 1.day
log.info tomorrow.format('yyyy-MM-dd')
}
编辑:基于 OP 评论
还有一个方法是动态添加方法,比如nextDay()
到Date
class.
//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