Vaadin 24中如何自定义Grid内时间戳的渲染格式?
在Vaadin 24 Grid中自定义时间戳显示格式
根据时间戳的存储类型,有几种常用的自定义渲染方式:
1. 时间戳为Long类型(毫秒数)
如果你的实体类中时间戳是以Long类型存储的毫秒数,直接用LambdaRenderer转换并格式化:
Grid<YourEntity> grid = new Grid<>(YourEntity.class); // 假设实体类有getTimestamp()方法返回Long型毫秒时间戳 grid.addColumn(new LambdaRenderer<>(YourEntity::getTimestamp, timestamp -> { if (timestamp == null) { return "-"; // 空值时显示占位符 } // 自定义时间格式,这里用yyyy-MM-dd HH:mm:ss DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); // 按需指定时区,比如ZoneId.of("Asia/Shanghai") return formatter.format(Instant.ofEpochMilli(timestamp)); })).setHeader("创建时间");
2. 时间戳为Java 8+时间类型(Instant/LocalDateTime等)
如果已经用Instant、LocalDateTime等类型存储时间,格式化更直接:
// 假设实体类getCreateTime()返回Instant类型 grid.addColumn(new LambdaRenderer<>(YourEntity::getCreateTime, time -> { if (time == null) { return ""; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); return formatter.format(time); })).setHeader("创建时间");
也可以用更简洁的写法:
grid.addColumn(entity -> { Instant time = entity.getCreateTime(); return time == null ? "" : DATE_TIME_FORMATTER.format(time); }).setHeader("创建时间");
3. 复用格式化规则
如果多个列需要相同的时间格式,建议把DateTimeFormatter抽成常量,避免重复创建:
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.of("Asia/Shanghai")); // 固定业务时区 // 使用时直接调用 grid.addColumn(entity -> DATE_TIME_FORMATTER.format(entity.getCreateTime())) .setHeader("创建时间");
注意事项
- 务必处理
null值,避免空指针异常 - 时区选择要符合业务场景,不要依赖系统默认时区(可能随环境变化)
- 格式模式可按需调整,比如
yyyy-MM-dd HH:mm:ss.SSS会显示毫秒级精度
内容的提问来源于stack exchange,提问作者Stimpson Cat
相关产品推荐
相关产品推荐

