【发布时间】:2021-12-03 00:37:49
【问题描述】:
我用 getDateAfter(int days) 方法编写了简单的 TimeService 并对其进行了测试:
@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);
}
}
您是否知道为什么我无法进行此测试以及其他可能出现问题的地方(我假设诸如编程语言如何处理步骤年等...)
【问题讨论】:
-
好吧,不知道
timeService.getDateAfter()是做什么的,很难说。您能否提供一个minimal reproducible example? -
默认时区中的当前时间首选
ZonedDateTIme而不是LocalDateTIme。
标签: java spring date time java-time