我有这个代码
Instant now = Instant.now();
if (amountDays >= 0) {
now = now.plus(amountDays, ChronoUnit.DAYS);
} else {
now = now.minus(Math.abs(amountDays), ChronoUnit.DAYS);
}
我想像这样简化它
Instant now = Instant.now();
now = now.plus(amountDays, ChronoUnit.DAYS);
但是,我不确定 plus
是否可以正确处理负值,或者是否会弄乱结果。
我可以像那样使用 plus
吗?可能是负值?
最佳答案
plus
负值
plus
方法支持添加负时间以回到过去,从它的 documentation :
amountToAdd - the amount of the unit to add to the result, may be negative
一切顺利,您可以像那样使用它,它会按预期工作。
实现
小知识,current implementation minus
甚至以 -amountToSubtract
作为值委托(delegate)给 plus
:
return (amountToSubtract == Long.MIN_VALUE
? plus(Long.MAX_VALUE, unit).plus(1, unit)
: plus(-amountToSubtract, unit));
注意事项
一般来说,如果您只是想回到过去,更喜欢使用 minus
以提高可读性。
在您的特定情况下,我会坚持使用 plus
,但不会不必要地膨胀代码和逻辑。相反,更喜欢添加评论
// amountDays may be negative
或确保您的 javadoc 清楚这一点。
小改进,您可以将代码从两个语句简化为一个:
Instant now = Instant.now().plus(amountDays, ChronoUnit.DAYS);
关于java - 即时加负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66137303/