TruncatedTo Buckets Timestamps
Bucket instants with truncatedTo for exact-duration units, fall back to epoch-second arithmetic for 15-minute windows, and learn where MONTHS throws.
Code
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
public class EventBucketer {
public static void main(String[] args) {
Instant event = Instant.parse("2026-11-19T09:47:31Z");
// Instant 的 truncatedTo 只接受时长精确的单位:timestamps 分桶到小时与天
System.out.println("hour bucket: " + event.truncatedTo(ChronoUnit.HOURS));
System.out.println("day bucket: " + event.truncatedTo(ChronoUnit.DAYS));
// 15 分钟分桶:没有对应 ChronoUnit,用 epoch 秒整除再落回 Instant
long bucketSeconds = (event.getEpochSecond() / 900) * 900;
System.out.println("15m bucket: " + Instant.ofEpochSecond(bucketSeconds));
// 日历单位不是固定时长:在 Instant 上 truncate 到月会直接抛异常
try {
event.truncatedTo(ChronoUnit.MONTHS);
} catch (UnsupportedTemporalTypeException e) {
System.out.println("months on Instant: " + e.getClass().getSimpleName());
}
// 按月分桶需要日历语义:先转成日期再取当月一号
var monthStart = event.atZone(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);
System.out.println("month bucket: " + monthStart);
}
}Inside the snippet
The snippet is organized around the class EventBucketer and the function main.
What to watch for
- Dependency-free by construction — no registry, no lockfile entry.
Using it
Entry signature: public static void main(String[] args)
Each run prints the 5 labeled blocks hour bucket:, day bucket:, 15m bucket:, months on Instant:, month bucket: in source order.
Key statements
var monthStart = event.atZone(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);
long bucketSeconds = (event.getEpochSecond() / 900) * 900;
Instant event = Instant.parse("2026-11-19T09:47:31Z");
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does TruncatedTo Buckets Timestamps print when run?
- Run it as a complete program — the output lines carry labels such as `hour bucket:`, `day bucket:`, `15m bucket:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.