What is the difference of using TemporalAmount or TemporalUnit in Java 8?

前提是你 提交于 2019-12-04 01:35:45

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.

If you look at the source, the plus(long amountToAdd, TemporalUnit unit) method uses the plusXXX methods to produce the results. So there are no arguments here about efficiency.

Instead, you use whichever is most appropriate for your scenario. I would suggest that if you are using user input to decide whether to add hours, minutes, etc., then the plus() method is better. Otherwise, your code might be easier to read if you use plusXXX.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!