我想把时间缩短到即将到来的15分钟时间。 例如:
2017-12-11T13:11:51.728Z
至2017-12-11T13:15:00.000Z
2017-12-11T13:21:51.728Z
至2017-12-11T13:30:00.000Z
Groovy代码:
def currentTime = context.expand('${#Project#currentTime}')
log.info currentTime
date1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(currentTime)
//Round off the time nearest to the mod 15
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 15;
log.info calendar.add(Calendar.MINUTE, mod < 8 ? -mod : (15-mod));
输出
Mon Dec 11 14:32:32 IST 2017:INFO:2017-12-11T14:32:32.690Z
Mon Dec 11 14:32:32 IST 2017:INFO:null
答案 0 :(得分:2)
你走了:
def timez = ['2017-12-11T13:11:51.728Z', '2017-12-11T13:21:51.728Z', '2017-12-11T13:30:00.000Z']
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def roundValue = 15
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
Calendar calendar = Calendar.getInstance()
def getNearestMinutes
//Closure which gets called recursive
getNearestMinutes = { cmin, nearMin = roundValue ->
def tempResult = cmin % nearMin
if ( tempResult < nearMin && (0 < (nearMin - cmin)) ) {
return (nearMin - cmin)
} else {
return getNearestMinutes(cmin, nearMin+roundValue)
}
}
//Loop thru times and round the time
timez.each {
calendar.time = Date.parse(dateFormat,it)
def currentMinute = calendar.get(Calendar.MINUTE)
def cof = currentMinute % roundValue
if (cof) {
currentMinute += getNearestMinutes(currentMinute)
calendar.set(Calendar.MINUTE, currentMinute )
}
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
log.info calendar.time.format(dateFormat)
}
您可以在线快速尝试 demo
编辑:感觉解决方案可以比在困难条件下应用更简单。
这是另一种解决方案,即将近一段时间到未来15分钟。
然而,与第一个解决方案中的多个条件不同,易于阅读的代码。
使用Switch statement
def timez = ['2017-12-11T13:11:51.728Z', '2017-12-11T13:21:51.728Z', '2017-12-11T13:30:00.000Z', '2017-12-11T13:46:00.000Z']
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def roundValue = 15
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
Calendar calendar = Calendar.getInstance()
def getNexTime = { min ->
def result
switch(min) {
case 1..15:
result = 15
break
case 16..30:
result = 30
break
case 31..45:
result = 45
break
case 46..60:
result = 60
break
default:
result = 0
break
}
result
}
//Loop thru times and round the time
timez.each {
calendar.time = Date.parse(dateFormat,it)
def currentMinute = calendar.get(Calendar.MINUTE)
if (0 != getNexTime(currentMinute)) {
calendar.set(Calendar.MINUTE, getNexTime(currentMinute) )
}
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
println calendar.time.format(dateFormat)
}