So Java 1.8 comes with a whole new (and old) bunch of classes to manage time calculations: java.time.Instant, java.time.LocalTime, java.time.temporal.ChronoUnit, and maybe more...
But why is there no simple way to calculate the time difference between any of these? I would expect "time_later - time_earlier" to be the most used manipulation of time, but this is nowhere to be seen. I cannot subtract one LocalTime from the other and get a new LocalTime; I cannot subtract one Instant from the other to get a new Instant. Instead I have to fiddle with ChronoUnits.between, and long milliseconds and whatnots to achieve this very useful thing.
Why is this? There has to be something going on that I do not get? Or I'm just daft...?
解决方案
Before Java 8, the usual answer to your question was "use Joda Time"
But the author of Joda Time (Stephen Colebourne) was deeply involved in the new Java 8 time classes and methods. Here are two very good articles:
For your specific question, you might want to consider Java 8 "Duration" and "LocalTime", "LocalDate" and/or "LocalTimeDate" (among other options):
// A duration of 3 seconds and 5 nanoseconds
Duration duration = Duration.ofSeconds(3, 5);
Duration oneDay = Duration.between(today, yesterday);
// Tomorrow
LocalDate tomorrow = LocalDate.now().plusDays(1);
// Yesterday
LocalDate yesterday = LocalDate.now().plusDays(-1);
// before 5 houres and 30 minutes
LocalDateTime dateTime = LocalDateTime.now().minusHours(5).minusMinutes(30);
探讨Java 8新时间类库中缺乏简单时间差计算方法的问题,介绍替代方案如Duration、LocalDate和LocalTime的使用,以及为什么这种设计选择存在。
1316

被折叠的 条评论
为什么被折叠?



