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.
Code
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
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.