📜  java.time.Duration类(1)

📅  最后修改于: 2023-12-03 15:31:35.084000             🧑  作者: Mango

Java.time.Duration Class

The java.time.Duration class is part of the Java 8 Date Time API that provides a way to represent a duration of time in hours, minutes, seconds, and nanoseconds. It was introduced as a replacement for the java.util.Date and java.util.Calendar classes.

Creating a Duration Object

You can create a Duration object in several ways:

Duration.of()

The of() method is a static factory method that creates a Duration object with the specified amount of time. For example, to create a duration of 2 hours and 30 minutes, you can use the following code:

Duration duration = Duration.ofHours(2).plusMinutes(30);
Duration.between()

The between() method is another way to create a Duration object. It takes two Temporal objects as parameters and returns the duration between them. For example, to calculate the duration between two Instant objects, you can use the following code:

Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();

Duration duration = Duration.between(start, end);
Operations on Duration

The Duration class provides several methods for performing arithmetic operations on duration objects:

plus() and minus()

The plus() and minus() methods add or subtract a Duration object from another Duration object. For example, to add 5 hours and 30 minutes to an existing duration, you can use the following code:

Duration duration = Duration.ofHours(2).plusMinutes(30);
Duration newDuration = duration.plus(Duration.ofHours(5).plusMinutes(30));
multipliedBy()

The multipliedBy() method multiplies the Duration object by a scalar value. For example, to multiply a duration object by 5, you can use the following code:

Duration duration = Duration.ofHours(2).plusMinutes(30);
Duration newDuration = duration.multipliedBy(5);
dividedBy()

The dividedBy() method divides the Duration object by a scalar value. For example, to divide a duration object by 2, you can use the following code:

Duration duration = Duration.ofHours(2).plusMinutes(30);
Duration newDuration = duration.dividedBy(2);
Retrieving Values from Duration

You can retrieve the number of hours, minutes, seconds, and nanoseconds from a Duration object using the following methods:

  • toHours()
  • toMinutes()
  • toSeconds()
  • toMillis()
  • toNanos()

For example, to retrieve the number of hours from a duration object, you can use the following code:

Duration duration = Duration.ofHours(2).plusMinutes(30);
long hours = duration.toHours();
Conclusion

The java.time.Duration class provides a way to represent a duration of time in hours, minutes, seconds, and nanoseconds. It provides several methods for performing arithmetic operations on duration objects and for retrieving values from those objects. It is a useful class for any Java programmer who needs to work with durations of time.