Course contentsShow
← Java
Lesson 1861 of 2,87038. Date and Time API (java.time)Free lesson

Extracting Duration Components: toHours, toMinutes, getSeconds

Retrieve individual components from a Duration such as total hours, minutes, seconds, and nanoseconds.

Extracting Duration Components: toHours, toMinutes, getSeconds

You'll learn how to retrieve individual time components from a Duration object to understand exactly how many hours, minutes, seconds, or nanoseconds it represents.

Understanding Component Extraction

Once you've created a Duration object, you often need to break it down into human-readable parts. The Duration class provides several methods to extract specific components:

  • toHours() – Returns the total number of whole hours
  • toMinutes() – Returns the total number of whole minutes
  • toSeconds() – Returns the total number of whole seconds
  • getSeconds() – Returns the seconds component (similar to toSeconds())
  • getNano() – Returns the nanoseconds part (0–999,999,999)

Think of a Duration like a length measured in millimeters. You can express that same length in centimeters, meters, or kilometers—each conversion gives you a different number representing the same quantity.

The "to" Methods: Total Amounts

Methods like toHours() convert the entire duration into that unit:

Duration duration = Duration.ofHours(2).plusMinutes(30);

long totalHours = duration.toHours();      // 2 (truncates fractional hours)
long totalMinutes = duration.toMinutes();  // 150 (2 hours × 60 + 30 minutes)
long totalSeconds = duration.toSeconds();  // 9000 (150 minutes × 60)

Notice how toHours() truncates—it doesn't round up. The duration is 2.5 hours, but you get 2.

The "get" Methods: Components

getSeconds() and getNano() work together to give you the full precision:

Duration d = Duration.ofSeconds(125, 500_000_000);

long seconds = d.getSeconds();  // 125
int nanos = d.getNano();         // 500000000 (0.5 seconds as nanos)

The seconds and nanoseconds are stored separately, so you often need both for complete information.

Key Takeaway: Use toHours(), toMinutes(), or toSeconds() to get total amounts in a specific unit, and use getSeconds() with getNano() to access the underlying components with full precision.