What is Duration.toString() in Java?
toString() is an instance method of the Duration class, which is used to get the string representation of the Duration object. The string will be in the ISO-8601 seconds-based format, i.e., PThHmMsS where h represents the value of hours, m represents the value of minutes, and s represents the value of seconds. If any unit has a value of zero , it is omitted.
Examples using different units of time are as follows:
| Duration | ISO-8601 Format |
|---|---|
| 3 seconds | PT3S |
| 4 minutes | PT4M |
| 4 days | PT96H |
| 4 hours | PT4H |
The toString() method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, use the following import statement:
import java.time.Duration;
Syntax
public String toString()
Parameters
This method takes no parameters.
Return value
This method returns an ISO-8601 representation of the specified duration.
Code
import java.time.Duration;public class Main{public static void main(String[] args) {System.out.println("Seconds Representation - " + Duration.ofSeconds((long) 3.422));System.out.println("Minutes Representation - " + Duration.ofMinutes(4));System.out.println("Days Representation - " + Duration.ofDays(4));System.out.println("Hours Representation - " + Duration.ofHours(4));}}