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

Duration Arithmetic: plus, minus, multipliedBy, dividedBy

Perform arithmetic operations on Duration objects to add, subtract, multiply, or divide time spans.

Duration Arithmetic: plus, minus, multipliedBy, dividedBy

You'll learn how to perform arithmetic operations on Duration objects to manipulate time spans programmatically.

What Is Duration Arithmetic?

Just like you can add, subtract, multiply, or divide numbers, you can perform similar operations on Duration objects. Since Duration is immutable, these operations don't modify the original—they return new Duration instances with the adjusted values. This lets you scale durations, combine them, or break them down as needed.

Core Operations

Adding and Subtracting

Use plus() and minus() to combine or reduce durations:

Duration twoHours = Duration.ofHours(2);
Duration thirtyMinutes = Duration.ofMinutes(30);

Duration total = twoHours.plus(thirtyMinutes);  // 2h 30m
Duration remaining = twoHours.minus(thirtyMinutes);  // 1h 30m

Multiplying and Dividing

Use multipliedBy() and dividedBy() to scale durations by a factor:

Duration oneHour = Duration.ofHours(1);

Duration tripled = oneHour.multipliedBy(3);  // 3 hours
Duration halved = oneHour.dividedBy(2);      // 30 minutes

These methods accept long values for the multiplier or divisor.

Practical Example

Think of baking: if a recipe needs 45 minutes and you're making three batches sequentially:

Duration batchTime = Duration.ofMinutes(45);
Duration totalTime = batchTime.multipliedBy(3);  // 2h 15m
Duration perItem = totalTime.dividedBy(36);      // If 36 items total

Chaining Operations

Since each operation returns a new Duration, you can chain them:

Duration adjusted = Duration.ofHours(8)
    .plus(Duration.ofMinutes(30))
    .dividedBy(2);  // (8h 30m) / 2 = 4h 15m

Key Takeaway: Duration arithmetic methods (plus, minus, multipliedBy, dividedBy) let you perform calculations on time spans, returning new immutable Duration objects for safe, predictable temporal math.