Home »
        Java »
        Java Reference »
        Java Duration Class
    
    Java Duration Class | toString() Method with Example
    
    
       
    
	    Duration Class toString() method: Here, we are going to learn about the toString() method of Duration Class with its syntax and example.
	    
		    Submitted by Preeti Jain, on May 17, 2020
	    
    
    Duration Class toString() method
    
        - toString() method is available in java.time package.
 
        - toString() method is used to denote this Duration as a String by using the standards ISO-8601 format like PT8H6M12.345S.
 
        - toString() method is a non-static method, it is accessible with class object only and if we try to access the method with class name then we will get an error.
 
        - toString() method may throw an exception at the time of representing this object as a string.
ArithmeticException: This exception may throw when the calculated exceed the length of this Duration. 
    
    
Syntax:
    public String toString();
    Parameter(s):
    
    
    Return value:
    The return type of this method is String, it represents this Duration as a String by using ISO-8601 standards format.
    
    Example:
// Java program to demonstrate the example 
// of String toString() method of Duration
import java.time.*;
public class ToStringOfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofHours(2);
        Duration du2 = Duration.parse("P0DT0H1M");
        // Display du1 and du2
        System.out.println("du1: " + du1);
        System.out.println("du2: " + du2);
 
        // represents this Duration du1 as a string
        String to_string = du1.toString();
        // Display to_string
        System.out.println("du1.toString(): " + to_string);
        // represents thisDuration du2 as a string
        to_string = du2.toString();
        // Display to_string
        System.out.println("du2.toString(): " + to_string);
    }
}
Output
du1: PT2H
du2: PT1M
du1.toString(): PT2H
du2.toString(): PT1M
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement