2016-07-27 20 views
1

我需要計算今天00:00 AM和明天00:00 AM。如何從給定的瞬間獲得兩個夜間?

我想喜歡這個

private static void some(final Date now) { 
    final Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(now); 
    calendar.set(Calendar.MILLISECOND, 0); 
    calendar.set(Calendar.SECOND, 0); 
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.HOUR_OF_DAY, 0); 
    final Date min = calendar.getTime(); // 00:00 AM of today 
    calendar.add(Calendar.DATE, 1); 
    final Date max = calendar.getTime(); // 00:00 AM of tomorrow 
} 

是否有這樣做的更好的任何(或其他簡單)的方式?

+0

你可以使用java時間API(java 8)嗎? – assylias

+0

@assylias是的! –

+0

@JinKwon你想在你的當地時區午夜?在UTC? – assylias

回答

3

你想要做的事情有幾個問題。

首先,「今天」對於Date不是一個明確的概念。 Date基本上只是Unix時代以來的毫秒數的包裝:對應於該時刻的日曆日期不同,取決於您所在的時區。

例如,由new Date(1469584693000)代表的時刻位於2016-07- 27歲在倫敦;但它在2016-07-26在紐約。

當然,您可以依賴JVM的默認時區,但這會使代碼的行爲依賴於JVM的配置。其次,「午夜」並不總是存在的:例如,「午夜」並不總是存在:例如,「午夜」並不總是存在。在Asia/Gaza時區,夏令時從午夜開始,這意味着時鐘從一天的23點59分59秒跳到下一天的01點00分(請參見Ideone demo)。這就是爲什麼Java 8時間API具有稱爲atStartOfDay而不是atMidnight的方法的原因。

所以,你可以把這個一起,在Java 8日:

private static void some(final Date now, ZoneId zone) { 
    Instant instant = now.toInstant(); // Convert from old legacy class to modern java.time class. 
    ZonedDateTime zdt = instant.atZone(zone); // Apply a time zone to the UTC value. 
    LocalDate today = zdt.toLocalDate(); // Extract a date-only value, without time-of-day and without time zone. 

    ZonedDateTime startOfDayToday = today.atStartOfDay(zone); // Determine first moment of the day. 
    ZonedDateTime startOfDayTomorrow = today.plusDays(1).atStartOfDay(zone); 

    // ... 
} 

當然,你可以直接通過在InstantZonedDateTime的方法;並且可以使用明確的常數ZoneId,例如, ZoneId.of("UTC")

相關問題