为什么Instant不支持使用ChronoUnit.YEARS进行操作? [英] Why Instant does not support operations with ChronoUnit.YEARS?
问题描述
这对我来说意外:
> Clock clock = Clock.systemUTC();
> Instant.now(clock).minus(3, ChronoUnit.DAYS);
java.time.Instant res4 = 2016-10-04T00:57:20.840Z
> Instant.now(clock).minus(3, ChronoUnit.YEARS);
java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
作为解决方法我有要做到这一点:
As a workaround I have to do this:
> Instant.now(clock).atOffset(ZoneOffset.UTC).minus(3, ChronoUnit.YEARS).toInstant();
java.time.Instant res11 = 2013-10-07T01:02:56.361Z
我很好奇为什么Instant不支持YEARS。开发人员是否放弃了它?
I am curios why Instant does not support YEARS. Did developers just give up on it?
(在我的实际代码中,我试图减去 Period.ofYears(3)
但是引用的Instant方法最后被调用了。)
(In my actual code I tried to subtract a Period.ofYears(3)
but the quoted Instant methods are the ones being called in the end).
推荐答案
我正在刺它看起来像是非常符合逻辑的东西。
I'm taking a stab at it in what looks to me like something very logical.
这是方法的代码 plus(long,TemporalUnit)
(用于减去(...)
):
Here is the code for the method plus(long, TemporalUnit)
(which is used in minus(...)
):
@Override
public Instant plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case NANOS: return plusNanos(amountToAdd);
case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
case MILLIS: return plusMillis(amountToAdd);
case SECONDS: return plusSeconds(amountToAdd);
case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));
case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));
case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));
case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
我们可以看到结果是通过乘以秒的单位表示来计算的,a由于显而易见的原因,年份不能以逻辑和一致的方式表示。
We can see that the results are calculated by multiplying seconds representation of units, a year cannot be logically and consistently represented by seconds for obvious reasons.
加法
我可以看到另一个明显的原因:上述方法中使用的常量来自 java.time.LocalTime
。常量仅定义单位为天。没有定义上面的常数(在 LocalDate
和 LocalDateTime
中)。
I can see another obvious reason why : constants used in the method above come from java.time.LocalTime
. The constants only define units up to days. No constant above days are defined (in LocalDate
and LocalDateTime
neither).
这篇关于为什么Instant不支持使用ChronoUnit.YEARS进行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!