在Java 8中使用TemporalAmount或TemporalUnit有什么区别? [英] What is the difference of using TemporalAmount or TemporalUnit in Java 8?
问题描述
我在Java 8中编写了一些使用时间算法的代码。
我意识到我可以在不同的方面实施。让我们看看下面的简单代码。当然它是相同的结果,但我混淆了哪种方式主要应用或最有效地在Java 8中进行算术运算?
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);
提前致谢。
推荐答案
持续时间
只能处理固定时间段,例如小时,分钟,秒,天(其中)假设每天24小时)。你不能在持续时间
中使用月,因为一个月的长度不一。
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.
期间
- 另一个常见的 TemporalAmount
实施 - 分别代表年,月和日。
Period
- the other common TemporalAmount
implementation - represents years, months and days separately.
我个人建议:
- 如果您事先知道该单位,请使用相应的
plusXxx
方法,例如time.plusMinutes(10)
。这很容易阅读。 - 当您尝试表示逻辑日历金额时,请使用
期间
- 当您尝试表示固定长度金额时,请使用
持续时间
- 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
以下是期间
和期限
可能不同的示例/ p>
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.
这篇关于在Java 8中使用TemporalAmount或TemporalUnit有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!