Java 1.8时间功能 [英] Java 1.8 time functionality

查看:105
本文介绍了Java 1.8时间功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,Java 1.8附带了一大堆新的(和旧的)类来管理时间计算: java.time.Instant java。 time.LocalTime java.time.temporal.ChronoUnit ,也许更多......

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...

但为什么没有简单的方法来计算其中任何一个之间的时差?我希望time_later - time_earlier是最常用的时间操纵,但这是无处可见的。我无法从另一个中减去一个LocalTime并获得一个新的LocalTime;我不能从另一个中减去一个瞬间来获得一个新的瞬发。相反,我必须摆弄ChronoUnits.between,以及长毫秒和其他什么来实现这个非常有用的东西。

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...?

推荐答案

在Java 8之前,你问题的通常答案是使用Joda Time

Before Java 8, the usual answer to your question was "use Joda Time"

  • http://joda-time.sourceforge.net/faq.html

但Joda Time(Stephen)的作者Colebourne)深入参与了新的Java 8时间类和方法。以下是两篇非常好的文章:

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:

  • http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

对于您的具体问题,您可能需要考虑Java 8持续时间和LocalTime,LocalDate和/或LocalTimeDate(以及其他)选项):

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 1.8时间功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆