Get Number of Minutes in a Duration in Java



In this article, we calculate the number of minutes in a given duration using Java. The Duration class can perform time-based calculations like hours, minutes, days, etc.. and easily convert between these units. Using the toMinutes() method you will be able to get the number of minutes from a given Duration.

Problem Statement

Given a Duration object representing a period of time, write a Java program to calculate the number of minutes in the specified duration.
Input
Duration = 25 days, 10 hours
Output
Minutes in 25 days = 36000
Minutes in 10 hours = 600

Steps to get the number of minutes from a duration

The following are the steps to get the number of minutes from a duration ?

  • Import the Duration class from the java.time package.
  • Create a Duration object for the required time period using methods like ofDays() and ofHours().
  • Use the toMinutes() method to convert the Duration to minutes.
  • Display the calculated minutes.

Java program to get the number of minutes from a duration

The following is an example of calculating the number of minutes in a given duration ?

import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      Duration d1 = Duration.ofDays(25);
      Duration d2 = Duration.ofHours(10);
      System.out.println("Minutes in 25 days = "+d1.toMinutes());
      System.out.println("Minutes in 10 hours = "+d2.toMinutes());
   }
}

Output

Minutes in 25 days = 36000
Minutes in 10 hours = 600

Code Explanation

The program creates two Duration objects; one of them for 25 days and the other for 10 hours. Then, the toMinutes() method is called for both of the Duration objects to convert the values of the durations in minutes. Then the results are printed out using System.out.println().

Updated on: 2024-11-18T22:30:42+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements