I basically want to get zero or beginning hour for currrent day.
def today = Calendar.instance
today.set(Calendar.HOUR_OF_DAY, 0)
today.set(Calendar.MINUTE, 0)
today.set(Calendar.SECOND, 0)
println today // Mon Mar 15 00:00:00 SGT 2010
I basically want to get zero or beginning hour for currrent day.
def today = Calendar.instance
today.set(Calendar.HOUR_OF_DAY, 0)
today.set(Calendar.MINUTE, 0)
today.set(Calendar.SECOND, 0)
println today // Mon Mar 15 00:00:00 SGT 2010
According to Groovy date documentation, it seems that it's the optimal way.
However, using Groovy with keyword, you can compress a little your statements
def today = Calendar.instance
with(today) {
set Calendar.HOUR_OF_DAY, 0
set Calendar.MINUTE, 0
set Calendar.SECOND, 0
}
println today // Mon Mar 15 00:00:00 SGT 2010
You could use the clearTime()
function of Calendar
in Groovy:
def calendar = Calendar.instance
calendar.with {
clearTime()
println time
}
It'd be nice to have a convenience method that clears the time portion of a
java.util.Date
and/orjava.util.Calendar
.
There are numerous use cases where it makes sense to compare month/day/year only portions of a calendar or date. Essentially, it would perform the following on Calendar:
void clearTime() {
clear(Calendar.HOUR_OF_DAY)
clear(Calendar.HOUR)
clear(Calendar.MINUTE)
clear(Calendar.SECOND)
clear(Calendar.MILLISECOND)
}
Not simpler than the other solutions, but less lines:
def now = new GregorianCalendar()
def today = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH))
println today.getTime()