Here you go:
- In order to get the difference minutes, created a closure.
- The closure gets called recursively if needed.
- If the current minutes is divisible by 15, it won't adjust the time; that is the reason for adding third value in the list.
- To be able to test with multiple values, used list of dates. You may use it for single value as well.
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)
}
You can quickly try it online demo
EDIT: Felt that the solution could be made something more simple than applying above difficult conditions.
Here is another solution to round time to near future 15 min.
Yet, easy to read code unlike multiple conditions in the first solution.
This is simple one using 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)
}
Date
andCalendar