开发者

Is there an easier way to get start of current day time than this?

开发者 https://www.devze.com 2022-12-23 02:33 出处:网络
I basically want to get zero or beginning hour for currrent day. def today = Calendar.instance today.set(Calendar.HOUR_OF_DAY, 0)

I basically want to get zero or beginning hour for currrent day.

def today = Calendar.instance
today.set(Calendar.HOUR_OF_DAY, 0)
tod开发者_StackOverflow中文版ay.set(Calendar.MINUTE, 0)
today.set(Calendar.SECOND, 0)
println today // Mon Mar 15 00:00:00 SGT 2010


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()


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/or java.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) 
 }


Yes, it would be nice to have to have such a method. But if you can settle for a short function then here's mine:

def startOfDay(t) {
    tz = TimeZone.getDefault();
    t +=tz.getOffset(t);
    t -= (t % 86400000);
    t-tz.getOffset(t);
}

print new Date(startOfDay(System.currentTimeMillis()));


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


Not quite sure if this is the best way, or indeed correct (not sure if timezone issues will arise from this), but it could work for simple use cases:

Start of day

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

End of day

def today = new Date()
def eod

use (TimeCategory) {
    eod = today.clearTime() + 1.day - 1.millisecond
}


Starting from Java 8 use java.time solution:

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

精彩评论

暂无评论...
验证码 换一张
取 消