YouTip LogoYouTip

Java Duration Class

Duration class is an important class in the date and time API introduced in Java 8 (java.time package), used to represent time intervals or durations. Duration class is mainly used to calculate the difference between two time points, or to represent a specific length of time. * * * ## Basic Concepts The time interval represented by Duration class can be precise to nanosecond level. It is mainly used to handle time-based quantities (hours, minutes, seconds, and nanoseconds), without involving the concept of dates or time zones. ### Main Features: 1. Immutability - Once a Duration object is created, it cannot be modified 2. Thread Safety - Can be safely used in multi-threaded environments 3. High Precision - Can be precise to nanosecond level 4. Method Chaining - Supports method chaining * * * ## Creating Duration Objects Duration class provides multiple static methods to create Duration instances: ### 1. Create by Time Unit ## Example // Create a Duration of 2 hours Duration twoHours = Duration.ofHours(2); // Create a Duration of 30 minutes Duration thirtyMinutes = Duration.ofMinutes(30); // Create a Duration of 45 seconds Duration fortyFiveSeconds = Duration.ofSeconds(45); // Create a Duration of 500 milliseconds Duration fiveHundredMillis = Duration.ofMillis(500); // Create a Duration of 1000000 nanoseconds Duration oneMillionNanos = Duration.ofNanos(1 _000_000); ### 2. Create by Time Amount ## Example // Create a Duration of 1 day, 2 hours, and 3 minutes Duration customDuration = Duration.ofDays(1).plusHours(2).plusMinutes(3); ### 3. Calculate from Two Time Points ## Example Instant start = Instant.now(); // Perform some operations... Instant end = Instant.now(); Duration elapsed = Duration.between(start, end); ### 4. Create by Parsing String ## Example // Create from ISO-8601 format string Duration parsedDuration = Duration.parse("PT2H30M15S");// 2 hours 30 minutes 15 seconds * * * ## Common Methods Duration class provides rich methods to handle time intervals: ### 1. Get Time Values ## Example Duration duration = Duration.ofHours(2).plusMinutes(30); long hours = duration.toHours();// 2 long minutes = duration.toMinutes();// 150 long seconds = duration.getSeconds();// 9000 int nanos = duration.getNano();// 0 ### 2. Time Operations ## Example Duration d1 = Duration.ofHours(2); Duration d2 = Duration.ofMinutes(30); // Addition Duration sum = d1.plus(d2);// 2 hours 30 minutes // Subtraction Duration diff = d1.minus(d2);// 1 hour 30 minutes // Multiplication Duration multiplied = d1.multipliedBy(3);// 6 hours // Division Duration divided = d1.dividedBy(2);// 1 hour ### 3. Comparison Operations ## Example Duration d1 = Duration.ofHours(1); Duration d2 = Duration.ofMinutes(90); boolean isEqual = d1.equals(d2);// false int comparison = d1.compareTo(d2);// -1 (d1 0){ System.out.println("Operation timeout"); break; } // Perform other operations... } ## Example import java.time.Duration; import java.time.LocalTime; import java.time.Instant; public class DurationDemo { public static void main(String[] args){ // Several ways to create Duration objects // 1. Use of...() method Duration duration1 = Duration.ofHours(2);// 2 hours Duration duration2 = Duration.ofMinutes(90);// 90 minutes System.out.println("Duration 1: "+ duration1); System.out.println("Duration 2: "+ duration2); // 2. Use between() method to calculate duration between two time points LocalTime startTime = LocalTime.of(9, 0); LocalTime endTime = LocalTime.of(11, 30); Duration duration3 = Duration.between(startTime, endTime); System.out.println("Duration between times: "+ duration3); // 3. Use parse() method to create from string Duration duration4 = Duration.parse("PT2H30M");// ISO-8601 format System.out.println("Parsed Duration: "+ duration4); // 4. Use Instant to calculate time difference Instant startInstant = Instant.now(); // Simulate time-consuming operation try{Thread.sleep(1500);}catch(InterruptedException e){} Instant endInstant = Instant.now(); Duration duration5 = Duration.between(startInstant, endInstant); System.out.println("Execution duration: "+ duration5.toMillis()+"ms"); } } Output: Duration 1: PT2H Duration 2: PT1H30M Duration between times: PT2H30M Parsed Duration: PT2H30M Execution duration: 1501ms * * * ## Notes 1. **Precision Issue**: Duration can be precise to nanosecond level, but the actual precision depends on the operating system and hardware support. 2. **Difference from Period**: * Duration is used to measure time-based hours, minutes, seconds, and nanoseconds * Period is used to measure date-based years, months, and days 3. **Immutability**: All Duration objects are immutable, and any modification operation will return a new Duration instance. 4. **Negative Value Handling**: Duration can represent negative time intervals, which may be encountered when calculating time differences. 5. **String Format**: Use ISO-8601 duration format `PnDTnHnMn.nS`, where: * P is the duration designator * D is the number of days * T is the time component separator * H is the number of hours * M is the number of minutes * S is the number of seconds (can have decimal part) * * * ## Summary Java's Duration class provides a powerful and flexible tool for handling time intervals. By mastering the use of the Duration class, developers can more easily handle various time-related calculation requirements, such as performance measurement, timeout control, task scheduling, etc. When used in combination with other date and time classes introduced in Java 8 (such as Instant, LocalDateTime, etc.), you can build more robust and readable time handling code.
← Java Inputstream ClassJava Instant Class β†’