迁移 org.joda.time 到 java.time

huangapple go评论57阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月17日 00:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定