Why Instant does not support operations with ChronoUnit.YEARS?

后端 未结 2 658
我在风中等你
我在风中等你 2021-02-03 18:00

This was unexpected to me:

> Clock clock = Clock.systemUTC();

> Instant.now(clock).minus(3, ChronoUnit.DAYS);
java.time.Instant res4 = 2016-10-04T00:57:20         


        
2条回答
  •  独厮守ぢ
    2021-02-03 18:38

    I guess it happens because Instant does not contain information about time zone. It means that same Instant can be interpreted as different date-time value in different time zones. Let's assume we have Instant which is is represented as 2016.01.01 00:30:00 in, let's say, UTC+2 time zone. The same Instant means 2015.12.31 23:30:00 in UTC+1 time zone. 2016 is a leap year, it's length is 366 days, so in order to get Instant minus 1 year, we have to subtract 366 days from it. But 2015 is not a leap year, it's length is 365 days, so we have to subtract 365 days from Instant. This ambiguity causes the fact that Instant does not support ChronoUnit.YEARS. Similar issue causes Instant to not support ChronoUnit.MONTHS. And probably absence of DST information causes Instant to not support ChronoUnit.WEEKS.

提交回复
热议问题