temporal java,在Java 8中使用TemporalAmount或TemporalUnit有什么区别?

I write some piece of code in Java 8 which use time arithmetic.

I realize that I can implement in differentways. Lets look at simple code below. Of course it is the same result but I confused which way is mostly applied or most efficient to make arithmetic operations in Java 8 ?

LocalTime time = LocalTime.now();

// 1st way

LocalTime plusOp = time.plus(Duration.ofMinutes(10L));

// 2nd way

LocalTime plusOp2 = time.plus(10L, ChronoUnit.MINUTES);

System.out.println(plusOp);

System.out.println(plusOp2);

// 3. way simply

time.plusMinutes(10L);

Thanks in advance.

解决方案

Duration can only handle fixed-length periods, such as "hours", "minutes", "seconds", "days" (where it assumes exactly 24 hours per day). You can't use "months" with Duration, because a month varies in length.

Period - the other common TemporalAmount implementation - represents years, months and days separately.

Personally I would recommend:

When you know the unit beforehand, use the appropriate plusXxx method, e.g. time.plusMinutes(10). That's about as easy to read as it gets.

When you're trying to represent "logical" calendar amounts, use Period

When you're trying to represent "fixed length" amounts, use Duration

Here's an example of where Period and Duration can differ:

import java.time.*;

public class Test {

public static void main(String[] args) {

ZoneId zone = ZoneId.of("Europe/London");

// At 2015-03-29T01:00:00Z, Europe/London goes from UTC+0 to UTC+1

LocalDate transitionDate = LocalDate.of(2015, 3, 29);

ZonedDateTime start = ZonedDateTime.of(transitionDate, LocalTime.MIDNIGHT, zone);

ZonedDateTime endWithDuration = start.plus(Duration.ofDays(1));

ZonedDateTime endWithPeriod = start.plus(Period.ofDays(1));

System.out.println(endWithDuration); // 2015-03-30T01:00+01:00[Europe/London]

System.out.println(endWithPeriod); // 2015-03-30T00:00+01:00[Europe/London]

}

}

I wouldn't worry about the efficiency until you really need to - at which point you should have a benchmark so you can test different options.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值