Open In App

Java DurationFormatUtils.formatDurationISO() Function

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The DurationFormatUtils class provides a convenient way to format durations in a human-readable format. The formatDurationISO() function is a part of this class & allows you to format durations in the ISO-8601 duration format. This format represents durations using the PnYnMnDTnHnMnS pattern. where P indicates the period & T separates the date & time components.

Note: you need to add the org.apache.commons.lang3 library to your project

Syntax of formatDurationISO() Function:

public static String formatDurationISO(long durationMillis)

Example of Java formatDurationISO() Function

Example 1 :

The formatDurationISO() function takes a duration in the milliseconds as input & returns a formatted string representation of the duration in the ISO-8601 format.

Java
// Java program to convert time into ISO format

import java.io.*;
import org.apache.commons.lang3.time.DurationFormatUtils;

//Driver Class
public class GFG {

      //Main method
    public static void main(String[] args) {

        // Define the duration in milliseconds
        long durationMillis = 3600000;
      
        // Convert the duration to a human-readable ISO format using DurationFormatUtils
        String formattedDuration = DurationFormatUtils.formatDurationISO(durationMillis);

        // Print the formatted duration with a descriptive message
        System.out.println("Formatted Duration: " + formattedDuration);
    }
}

Output:

Formatted Duration: PT1H

Explanation of the above Program:

The formatDurationISO() function formats the duration of 1 hour (3600000 milliseconds) into ISO-8601 duration format "PT1H", indicating 1 hour.

Example 2:

The formatDurationISO() function takes a duration in the milliseconds as input & returns a formatted string representation of the duration in the ISO-8601 format.

Java
// Java program to convert time into ISO-8601 duration
// format

import java.io.*;
import org.apache.commons.lang3.time.DurationFormatUtils;

// Driver class
public class GFG {

    // Main method
    public static void main(String[] args)
    {

        // Define the duration in milliseconds
        long durationMillis = 86400000;

        // Convert the duration to a human-readable format
        // using DurationFormatUtils
        String formattedDuration
            = DurationFormatUtils.formatDurationISO(durationMillis);

        // Print the formatted duration
        System.out.println("Formatted Duration: "
                           + formattedDuration);
    }
}

Output:

Formatted Duration: P1D

Explanation of the above Program:

The formatDurationISO() function formats the duration of the 1 day (86400000 milliseconds) into ISO-8601 duration format "P1D", indicating 1 day.



Next Article
Article Tags :
Practice Tags :

Similar Reads