ChronoUnit Between Unit Conversion
Measure spans between temporal values with ChronoUnit.between, choosing units from days down to nanos and watching truncation toward zero.
Code
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
public class SpanMeasurer {
public static void main(String[] args) {
LocalDateTime deploy = LocalDateTime.of(2026, Month.NOVEMBER, 1, 9, 30, 0);
LocalDateTime rollback = LocalDateTime.of(2026, Month.NOVEMBER, 3, 17, 45, 10);
// between(target, source) 或 between(source, target):单位决定粒度
System.out.println("days = " + ChronoUnit.DAYS.between(deploy, rollback));
System.out.println("hours = " + ChronoUnit.HOURS.between(deploy, rollback));
System.out.println("minutes= " + ChronoUnit.MINUTES.between(deploy, rollback));
// 大单位装不下的小数部分被截断:不四舍五入
Instant start = Instant.parse("2026-11-01T00:00:00.500Z");
Instant end = Instant.parse("2026-11-01T00:00:01.900Z");
System.out.println("seconds= " + ChronoUnit.SECONDS.between(start, end));
System.out.println("millis = " + ChronoUnit.MILLIS.between(start, end));
// Duration 也能问同样的跨度,两者等价
Duration span = Duration.between(start, end);
System.out.println("duration seconds = " + span.getSeconds());
}
}What the code does
ChronoUnit Between Unit Conversion comes down to the class SpanMeasurer and the function main.
Using it
The run emits 6 labeled sections — days =, hours =, minutes=, seconds=, millis =, duration seconds = — one per step.
Key statements
LocalDateTime rollback = LocalDateTime.of(2026, Month.NOVEMBER, 3, 17, 45, 10);
LocalDateTime deploy = LocalDateTime.of(2026, Month.NOVEMBER, 1, 9, 30, 0);
Instant start = Instant.parse("2026-11-01T00:00:00.500Z");
Interactive Tools for This Topic
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.
FAQ
- What does ChronoUnit Between Unit Conversion print when run?
- Invoke the file as-is — the `days =`, `hours =`, `minutes=` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.