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.

JavaData Integrity

Code

snippet
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

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:`.