英文:
Migrate org.joda.time to java.time
问题
我需要将这段代码迁移到这样的代码:
private int calculate(OffsetDateTime expirationDate) {
return (int) Duration.between(OffsetDateTime.now(), expirationDate).getSeconds();
}
英文:
I need to migrate also this code:
private int calculate(OffsetDateTime expirationDate) {
return Seconds.secondsBetween(DateTime.now(), expirationDate).getSeconds();
}
to this code:
private int calculate(OffsetDateTime expirationDate) {
return Duration.between(OffsetDateTime.now(), expirationDate).getSeconds();
}
getSeconds
returns long. is there some better way to get int?
答案1
得分: 2
如果你__确定__它不可能是这么大的间隔,只需强制转换为int。这种有点丑陋的'int'强制转换在代码中是你或其他人做出假设的明显标志,认为这不会成为问题。换句话说,这种强制转换是一件好事。
如果你不太确定,想要一个异常而不是这个,你必须编程处理。幸运的是,Java有一个内置的函数用于此:
return java.lang.Math.toIntExact(Duration.between....);
如果返回的数量非常大,将其强制转换为int
会溢出,它会抛出异常。
英文:
No; it is trivially imaginable that the gap, in seconds, between 2 OffsetDateTime objects is more than 2^31-1 seconds. (more than about 4 billion).
If you know it cannot possibly be such a large gap, just cast to int. The somewhat ugly 'int' cast is your visible sign in the code that somebody made an assumption that it won't be a problem. In other words, that cast is a GOOD thing.
If you're not quite sure and you want an exception instead, you have to program that. Fortunately, Java has a built-in function for this:
return java.lang.Math.toIntExact(Duration.between....);
That will throw if the returned amount is so large, casting it to an int
would overflow the value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论