java1.8时间好处,Java 1.8时间功能

探讨Java 8新时间类库中缺乏简单时间差计算方法的问题,介绍替代方案如Duration、LocalDate和LocalTime的使用,以及为什么这种设计选择存在。

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);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值