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

I am writing a piece of code in Java 8 using temporary arithmetic. I understand that I can implement in different ways. Let's look at the simple code below. Of course, this is the same result, but I confused which method is mainly used or most effective for performing 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.

+8
java datetime java-8 java-time
source share
2 answers

Duration can handle periods of fixed length, such as hours, minutes, seconds, days (where it takes exactly 24 hours a day). You cannot use β€œmonths” with Duration because the month varies in length.

Period - another common implementation of TemporalAmount - represents years, months and days separately.

Personally, I would recommend:

  • When you know the device in advance, use the appropriate plusXxx method, for example. time.plusMinutes(10) . It is about as easy to read as it turns out.
  • When you try to present the β€œlogical” amounts of a calendar, use Period
  • When you are trying to represent fixed-length amounts, use Duration

Here is an example of where Period and Duration may 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 would not worry about efficiency until you need it - at this point you should have a standard so that you can test various parameters.

+12
source share

If you look at the source, the plus(long amountToAdd, TemporalUnit unit) method plus(long amountToAdd, TemporalUnit unit) uses the plusXXX methods to get the results. Thus, there is no argument regarding effectiveness.

Instead, you use what works best for your scenario. I would suggest that if you use user input to decide whether to add hours, minutes, etc., it is better to use the plus() method. Otherwise, your code may be easier to read if you are using plusXXX .

+3
source share

All Articles