Duration Arithmetic Scales And Signs

Scale spans with Duration.dividedBy, count whole occurrences of a sub-span, and flip signs with negated and abs — zero divisor throws, not yields infinity.

JavaData Integrity

Code

snippet
import java.time.Duration;

public class DurationMath {

    public static void main(String[] args) {
        Duration meeting = Duration.ofMinutes(65);

        // dividedBy(long):整除缩放,65 分钟分 3 段每段 21 分钟(余数丢弃)
        System.out.println("one third: " + meeting.dividedBy(3));

        // dividedBy(Duration):问"装得下几个完整小段",向零取整
        long slots = meeting.dividedBy(Duration.ofMinutes(15));
        System.out.println("15-min slots: " + slots);

        // 除零抛 ArithmeticException,而不是得到无穷
        try {
            meeting.dividedBy(0);
        } catch (ArithmeticException e) {
            System.out.println("divided by zero rejected");
        }

        // negated() 变号:把"迟到 10 分钟"变成"提前 10 分钟"
        Duration late = Duration.ofMinutes(10);
        System.out.println("early by: " + late.negated());

        // abs() 取正:Duration.between 的结果可能为负,取绝对值再展示
        Duration between = Duration.between(
                java.time.Instant.parse("2026-11-23T10:00:00Z"),
                java.time.Instant.parse("2026-11-23T09:30:00Z"));
        System.out.println("raw: " + between + ", abs: " + between.abs());
    }
}

Inside the snippet

All of the logic lives in the class DurationMath and the function main.

What to watch for

  • Dependency-free by construction — no registry, no lockfile entry.

Using it

The entry-point signature is public static void main(String[] args)

The file’s steps show up in the output as one third:, 15-min slots:, divided by zero rejected.

Key statements

long slots = meeting.dividedBy(Duration.ofMinutes(15));
Duration meeting = Duration.ofMinutes(65);
Duration late = Duration.ofMinutes(10);

Interactive Tools for This Topic

FAQ

What does Duration Arithmetic Scales And Signs print when run?
No setup needed: run the file and look for labeled lines like `one third:`, `15-min slots:`, `divided by zero rejected` in the output.