Is there an easier way to get the start of the current daytime than this?

Basically I want to get the zero or start hour for day to 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 
+7
java datetime groovy calendar
source share
6 answers

Not easier than other solutions, but fewer 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() 
+7
source share

You can use the clearTime() Calendar function in Groovy:

 def calendar = Calendar.instance calendar.with { clearTime() println time } 

It would be nice to have a convenient method that clears the temporary part of java.util.Date and / or java.util.Calendar .
There are many use cases where it makes sense to compare only parts of the calendar or dates of the month / day / year. Essentially, on the calendar, he did the following:

 void clearTime() { clear(Calendar.HOUR_OF_DAY) clear(Calendar.HOUR) clear(Calendar.MINUTE) clear(Calendar.SECOND) clear(Calendar.MILLISECOND) } 
+5
source share

Yes, it would be nice to have such a method. But if you can agree to a short function, then here is mine:

 def startOfDay(t) { tz = TimeZone.getDefault(); t +=tz.getOffset(t); t -= (t % 86400000); t-tz.getOffset(t); } print new Date(startOfDay(System.currentTimeMillis())); 
+2
source share

According to Groovy's date , this seems like the best way.

However, using Groovy with , you can compress your statements a bit

 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 
+1
source share

Not quite sure if this is the best way or really the right one (not sure if there will be problems with the time zone), but it can work in simple cases:

The beginning of the day

 def today = new Date() def start = today.clearTime() 

End of the day

 def today = new Date() def eod use (TimeCategory) { eod = today.clearTime() + 1.day - 1.millisecond } 
0
source share

Starting with Java 8, use the java.time solution:

 LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.MIN); ldt.toString(); 
0
source share

All Articles