Java Duration toMinutes()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

In this guide, you will learn about the Duration toMinutes() method in Java programming and how to use it with an example.

1. Duration toMinutes() Method Overview

Definition:

The Duration.toMinutes() method is employed to obtain the total number of minutes represented by this duration, including both the whole hours and minutes.

Syntax:

public long toMinutes()

Parameters:

- None.

Key Points:

- The method returns the total count of minutes in the Duration.

- This includes both the whole hours (converted to minutes) and any additional minutes.

- A negative Duration will result in a negative returned value.

- This method can be useful for operations that require durations in minute granularity or when displaying the duration in minutes.

2. Duration toMinutes() Method Example

import java.time.Duration;

public class DurationToMinutesExample {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofHours(2).plusMinutes(30); // 2 hours and 30 minutes
        Duration duration2 = Duration.ofHours(-1).minusMinutes(15); // -1 hour and 15 minutes

        // Convert durations to minutes
        long minutes1 = duration1.toMinutes();
        long minutes2 = duration2.toMinutes();

        // Print the minutes
        System.out.println("Duration1 in minutes: " + minutes1);
        System.out.println("Duration2 in minutes: " + minutes2);
    }
}

Output:

Duration1 in minutes: 150
Duration2 in minutes: -75

Explanation:

In the example, duration1 is constructed with a total of 2 hours and 30 minutes. When toMinutes() is called, it returns 150 which is the total minutes (120 minutes from the 2 hours and 30 additional minutes).

For duration2, which is -1 hour and 15 minutes, the toMinutes() method gives -75 as the result. This is because 1 hour has 60 minutes, so the total becomes -60 - 15 = -75 minutes.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare