实现说明
TruncatedTo 时间戳分桶可以归结为类 EventBucketer和函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
hour bucket:、day bucket:、15m bucket:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「TruncatedTo 时间戳分桶」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 hour bucket:、day bucket:、15m bucket: 这类标签。
核心语句
var monthStart = event.atZone(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);
long bucketSeconds = (event.getEpochSecond() / 900) * 900;
Instant event = Instant.parse("2026-11-19T09:47:31Z");
代码示例
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);
}
}