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

Creating Duration Objects: ofDays, ofHours, ofMinutes, ofSeconds

Learn factory methods for creating Duration instances representing spans of hours, minutes, seconds, and nanoseconds.

Creating Duration Objects: ofDays, ofHours, ofMinutes, ofSeconds

You'll learn how to create Duration instances using convenient factory methods that represent specific time spans.

The Core Idea

A Duration represents an amount of time measured in seconds and nanoseconds. While you could always express everything in seconds, Java provides intuitive factory methods that let you think in natural units: days, hours, minutes, or seconds. These static methods make your code more readable and self-documenting.

Think of it like specifying a cooking time: you wouldn't say "bake for 5,400 seconds" when "bake for 90 minutes" is clearer. Java's factory methods work the same way.

Factory Methods for Duration

Each method creates a Duration internally converted to seconds and nanoseconds:

// 3 days worth of seconds
Duration threeDays = Duration.ofDays(3);

// 2 hours worth of seconds
Duration twoHours = Duration.ofHours(2);

// 45 minutes worth of seconds
Duration fortyFiveMinutes = Duration.ofMinutes(45);

// Directly specify seconds
Duration thirtySeconds = Duration.ofSeconds(30);

// Seconds with nanosecond precision
Duration preciseTime = Duration.ofSeconds(5, 123456789);

Why Multiple Factory Methods?

All durations are stored the same way internally, but having multiple methods improves readability:

Duration cacheTimeout = Duration.ofMinutes(15);  // Clear intent
Duration sessionLimit = Duration.ofHours(2);     // Obvious meaning

These methods also accept negative values for representing time in the past or backwards calculations.

Key Takeaway: Use Duration.ofDays(), ofHours(), ofMinutes(), and ofSeconds() factory methods to create time-based durations with clear, readable intent—all are converted internally to seconds and nanoseconds for precise calculations.