Duration in java is a class used to measure time in seconds and nanoseconds. The package of the duration class in java is java.time.Duration. The Duration class object specifies the period of time or is used to determine the difference between two times. A Duration object is immutable and thread-safe also as the Duration object is immutable, so we cannot change its values once it is created. But, we can create new Duration objects based on another Duration object. The Duration class inherits an object class ( as an object is the superclass of all classes in java) and implements the Comparable interface.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax
The syntax of the Duration class declaration in java is:
public final class Duration extends Object implements Comparable , TemporalAmount, Serializable { // variables and method of the class Duration}
Lists of Duration
The lists of Duration class methods are explained below with example code; an example code can be used further for similar methods (as for each method example code not given):
- Duration abs(): This method returns a copy of this duration with a positive length.
- long get(TemporalUnit unit): Return the value of the requested unit.
- static duration between(Temporal startInclusive, Temporal endExclusive): Return duration object, which is the duration between two temporal objects.
Example #1
We understand the above methods with the below sample java code.
Code:
package p1; import java.time.Duration; import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN); System.out.println(d.get(ChronoUnit.SECONDS)); Duration absd = d.abs(); System.out.println(absd.get(ChronoUnit.SECONDS)); } }
Output:
- Temporal addTo(Temporal temporal): Return duration object, which is the addition of temporal and this duration object.
- Duration dividedBy(long divisor): Return the duration object, which is this duration divided by the divisor.
Example #2
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN); LocalDateTime date = LocalDateTime.now(); System.out.println(date); date = (LocalDateTime)d.addTo(date); System.out.println(date); Duration d1 = d.dividedBy(4); System.out.println(d1); System.out.println(d.getSeconds()); System.out.println(d1.getSeconds()); } }
Output:
- int compareTo(Duration otherDuration): This duration and specified duration compares.
- boolean equals(Object otherDuration): Checks this duration with specified Duration and returns Boolean.
- boolean isNegative(): Return True if this duration is negative.
- boolean isZero(): Return True if this duration length is zero.
Example #3
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX); Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MIN); System.out.println(d1.getSeconds()); System.out.println(d.compareTo(d1)); System.out.println(d1.compareTo(d1)); System.out.println(d1.compareTo(d)); System.out.println(d1.equals(d)); System.out.println(d1.isNegative()); System.out.println(d1.isZero()); } }
Output:
- static duration from(TemporalAmount amount): Obtains an instance of duration from a temporal amount.
Example #4
We understand the above method with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.from(ChronoUnit.DAYS.getDuration()); System.out.println(d.toMinutes()); } }
Output:
- int getNano(): Return duration in nanoseconds.
- long getSeconds(): Return duration in seconds.
-
List
getUnits(): Return set of units supported by this duration. - int hashCode(): Return hash code for this duration.
Example #5
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX); System.out.println(d.getUnits()); System.out.println(d.toMinutes()); System.out.println(d.getSeconds()); System.out.println(d.getNano()); System.out.println(d.getClass()); } }
Output:
- Duration minus(Duration duration):- Returns object which results from this duration subtracted with the specified duration.
- Duration minus(long amountToSubtract, TemporalUnit unit): Returns object resulting from this duration subtracted with the specified duration.
- Duration minusDays(long daysToSubtract): Returns object which results from this duration subtracted with the specified duration in standard 24-hour days.
- Duration minusHours(long hoursToSubtract): Returns object resulting from this duration subtracted with the specified duration in hours.
- Duration minusMillis(long millisToSubtract): Returns object resulting from this duration subtracted with the specified duration in milliseconds.
- Duration minusMinutes(long minutesToSubtract): Returns object resulting from this duration subtracted with the specified duration in minutes.
- Duration minusNanos(long nanosToSubtract): Returns object resulting from this duration subtracted with the specified duration in nanoseconds.
- Duration minusSeconds(long secondsToSubtract): Returns object resulting from this duration subtracted with the specified duration in seconds.
- Duration multipliedBy(long multiplicand): Returns object resulting from this duration multiplied by the scalar.
- Duration negated() – Returns object which results from this duration with the length negated.
- static duration of(long amount, TemporalUnit unit): Returns Duration object representing an amount in the specified unit.
- static Duration ofDays(long days): Returns Duration object of standard 24-hour days.
- static Duration ofHours(long hours): Returns Duration object of the hour.
- static Duration ofMillis(long millis): Returns Duration object of milliseconds.
- static Duration ofMinutes(long minutes): Returns Duration object of minutes.
- static Duration ofNanos(long nanos): Returns Duration object of nanoseconds.
- static Duration ofSeconds(long seconds): Returns Duration object of seconds.
- static Duration ofSeconds(long seconds, long nanoAdjustment): Returns Duration object of seconds and nanoseconds adjustment.
Example #6
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.ofDays(6); System.out.println(d.getSeconds()); Duration d1 = d.minusDays(3); System.out.println(d1.getSeconds()); d = Duration.ofHours(6); System.out.println(d.getSeconds()); d1 = d.minusHours(2); System.out.println(d1.getSeconds()); } }
Output:
- static Duration parse(CharSequence text): Return duration object from a text, for example, PnDTnHnMn.nS.
- Duration plus(Duration duration): Return the duration object of this duration with added the specified duration.
- Duration plus(long amountToAdd, TemporalUnit unit): Return the duration object of this duration with add the specified duration.
- Duration plusDays(long daysToAdd): Return the duration object of this duration with add the specified duration in 24-hour days.
- Duration plusHours(long hoursToAdd): Return the duration object of this duration with add the specified duration in hours.
- Duration plusMillis(long millisToAdd): Return the duration object of this duration with add the specified duration in milliseconds.
- Duration plusMinutes(long minutesToAdd): Return the duration object of this duration with the add specified duration in minutes.
- Duration plusNanos(long nanosToAdd): Return the duration object of this duration with add the specified duration in nanoseconds.
- Duration plusSeconds(long secondsToAdd): Return the duration object of this duration with the specified duration in seconds.
Example #7
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.ofDays(6); System.out.println(d.getSeconds()); Duration d1 = d.plusDays(2); System.out.println(d1.getSeconds()); d = Duration.ofHours(6); System.out.println(d.getSeconds()); d1 = d.plusHours(2); System.out.println(d1.getSeconds()); } }
Output:
- Temporal subtractFrom(Temporal temporal): Return Subtraction of this duration from the temporal object.
- long toDays(): Return the number of days in this duration.
- long toHours(): Return the number of hours in this duration.
- long toMillis(): Return the number of milliseconds in this duration.
- long toMinutes(): return the number of minutes in this duration.
- long toNanos(): return the number of nanoseconds in this duration.
- String toString(): Return this duration in string representation, such as PT8H6M12.345S.
Example #8
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.ofDays(6); System.out.println(d.toHours()); Duration d1 =Duration.ofHours(24) ; System.out.println(d1.toDays()); } }
Output:
- Duration withNanos(int nanoOfSecond): Returns duration object with the specified nanoofsecond.
- Duration withSeconds(long seconds): Returns duration object of this duration with the seconds of the specified amount.
Example #9
We understand the above methods with the below sample java code:
Code:
package p1; import java.time.Duration; import java.time.*; import java.time.temporal.ChronoUnit; public class DurationClassDemo { public static void main(String[] args) { Duration d = Duration.ofDays(6); System.out.println(d.toString()); d = d.withSeconds(3000); System.out.println(d.toString()); } }
Output:
Conclusion
The Duration class is one of the built-in class in java, which is used to measure time in seconds and nanoseconds and add, subtract, and convert the duration, or, in simple words, the duration class allows performance operation on time or day duration. The duration class is available in java.time.Duration package of java.
The above is the detailed content of Java Duration. For more information, please follow other related articles on the PHP Chinese website!

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
