gpt4 book ai didi

java - 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象获取秒数?

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:39 29 4
gpt4 key购买 nike

我在从两个 LocalDateTime 对象获取秒数时遇到问题。

// a timestammp for the time when the connection was established
public LocalDateTime establish() {

startTime = LocalDateTime.now();
connectionEstablished = true;

return startTime;
}

// timestamp for the time when the connection was disconnected
public LocalDateTime disconnect() {

endTime = LocalDateTime.now();
connectionDisconnected = true;

return endTime;
}
// get the second when the connection was established
public LocalDateTime getStartTime() {

}

// get the seconds when the connection was disconnected
public LocalDateTime getEndTime() {

}

在方法 getStartTime() 和 getEndTime 中,返回类型必须来自 LocalDateTime。我尝试了不同的方法,例如使用 Duration. Between、使用 Temporal 作为返回类型,但它不起作用,因为 Junit 测试给出了返回类型必须是 LocalDateTime 的错误。

这是 Junit 测试:

    @Test
void test() throws InterruptedException {
cdr.establish();
System.out.println(cdr.toString());
assertTrue(cdr.toString().matches("calling: \\+44 44\\/725 8912, called: \\+1 982\\/543 1201, start: " + TIMESTAMP_PATTERN + ", end: still established"));
assertEquals(0.0, Duration.between(cdr.getStartTime(), LocalDateTime.now()).getSeconds(), 0.1);
assertNull(cdr.getEndTime());
Thread.sleep(1000);
cdr.establish();
// it fails here
assertEquals(1.0, Duration.between(cdr.getStartTime(), LocalDateTime.now()).getSeconds(), 0.1);
Thread.sleep(1000);
cdr.disconnect();
System.out.println(cdr.toString());
assertTrue(cdr.toString().matches("calling: \\+44 44\\/725 8912, called: \\+1 982\\/543 1201, start: " + TIMESTAMP_PATTERN + ", end: " + TIMESTAMP_PATTERN));
assertEquals(2.0, Duration.between(cdr.getStartTime(), cdr.getEndTime()).getSeconds(), 0.1);
Thread.sleep(1000);
cdr.disconnect();
assertEquals(2.0, Duration.between(cdr.getStartTime(), cdr.getEndTime()).getSeconds(), 0.1);
}

感谢任何帮助。谢谢!

最佳答案

您正在正确获取两个本地日期时间之间的秒数。测试的目的是确保当第二次调用 built 时(即当连接已经建立时),startTime 不会重置。测试基本上说:

One second later, establish the connection again, the start time should be 1 second before now (, as opposed to exactly now).

您可能应该更改建立方法:

public LocalDateTime establish() {
if (!connectionEstablished) { // add this check
startTime = LocalDateTime.now();
}
connectionEstablished = true;

return startTime;
}

关于java - 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象获取秒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771262/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com