我用方法撰寫了簡單的 TimeServicegetDateAfter(int days)并對其進行了測驗:
@Test
@Order(7)
public void getDateAfterCorrect() throws InterruptedException {
waitIfNeeded();
LocalDateTime today = LocalDateTime.now();
LocalDateTime tomorrow = timeService.getDateAfter(1).toInstant()
.atZone(ZoneId.systemDefault()).toLocalDateTime();
long diff = ChronoUnit.SECONDS.between(today, tomorrow);
long secondsAtDay = 86400;
Assertions.assertEquals(secondsAtDay, diff);
}
一天應該是 86400 秒,但是diff是 86399。我試圖通過實作waitIfNeeded()方法考慮到一部分代碼可以在另一個時間執行
private void waitIfNeeded() throws InterruptedException {
var currentMillis = Instant.now().get(ChronoField.MILLI_OF_SECOND);
if (currentMillis > 500) {
Thread.sleep(1000 - currentMillis);
}
}
您知道為什么我無法進行此測驗以及其他可能出錯的事情嗎(我假設諸如編程語言如何處理步驟年之類的事情等......)
uj5u.com熱心網友回復:
我設法簡化了測驗并使其正常作業,現在可以了:
@Test
@Order(7)
public void getDateAfterCorrect() throws InterruptedException {
waitIfNeeded();
long today = timeService.getDate().toInstant().getEpochSecond();
long tommorow = timeService.getDateAfter(1).toInstant().getEpochSecond();
Assertions.assertEquals(86400, tommorow - today);
}
但是為什么用其他方法比較兩個日期會產生這樣的結果仍然很有趣,如果知識淵博的人可以回答它,可能很少有人會感興趣。
uj5u.com熱心網友回復:
該java.util日期時間API已經過時,而且容易出錯。建議完全停止使用它并切換到現代 Date-Time API *。
除此之外,您不是自己執行計算(減法),而是使用Instant#untilwhich 回傳指定的持續時間ChronoUnit。
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// This is a sample Instant. In your case, it will be returned by
// timeService.getDate().toInstant()
Instant today = Instant.now();
// This is a sample Instant after one day. In your case, it will be returned by
// timeService.getDateAfter(1).toInstant()
Instant tomorrow = today.plus(1, ChronoUnit.DAYS);
long seconds = today.until(tomorrow, ChronoUnit.SECONDS);
// In your case, you will use Assertions.assertEquals(86400, seconds);
System.out.println(seconds);
}
}
輸出:
86400
ONLINE DEMO
從Trail: Date Time 中了解有關現代日期時間 API 的更多資訊。
* 如果您正在為 Android 專案作業并且您的 Android API 級別仍然不符合 Java-8,請檢查通過 desugaring 可用的 Java 8 API。請注意,Android 8.0 Oreo 已提供對java.time.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314118.html
