Spring Boot中如何格式化Holiday列表中LocalDateTime类型的updated字段
方案1:后端用Java Stream实现格式化(符合你的需求)
如果你需要在后端完成格式化操作,可以按以下步骤实现:
- 先给
Holiday实体类新增一个非持久化的字段,用于存储格式化后的时间字符串,避免修改原updated字段的类型:
// 根据你的Spring Boot版本导入对应的Transient注解:javax.persistence.Transient / jakarta.persistence.Transient @Transient private String formattedUpdated; // 新增对应的getter和setter public String getFormattedUpdated() { return formattedUpdated; } public void setFormattedUpdated(String formattedUpdated) { this.formattedUpdated = formattedUpdated; }
- 改造Controller代码,用Stream遍历列表完成格式化赋值:
@GetMapping("/getAllHolidays") public String getAllHolidays(Model theModel) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); List<Holiday> theHolidays = holidayService.findAll().stream() // 遍历每个Holiday对象,给格式化字段赋值 .peek(holiday -> holiday.setFormattedUpdated(holiday.getUpdated().format(formatter))) // JDK16以下版本替换为.collect(Collectors.toList()) .toList(); theModel.addAttribute("holidays", theHolidays); return "holidays"; }
- Thymeleaf页面直接使用格式化后的字段即可:
<th:block th:each="holiday : ${holidays}"> <p th:text="${holiday.formattedUpdated}"></p> </th:block>
如果不允许修改原有实体类,也可以定义DTO类做属性转换,用Stream的map方法实现实体到DTO的转换:
// 定义HolidayDTO public class HolidayDTO { private String holidayTitle; private String holidayDate; private String updated; // 存储格式化后的时间字符串 private String country; // 构造方法、getter、setter省略 } // Controller中转换逻辑 List<HolidayDTO> theHolidays = holidayService.findAll().stream() .map(holiday -> new HolidayDTO( holiday.getHolidayTitle(), holiday.getHolidayDate(), holiday.getUpdated().format(formatter), holiday.getCountry() )) .toList();
方案2:Thymeleaf端直接格式化(纯展示场景更推荐)
如果格式化仅用于页面展示,不需要后端额外处理格式化后的字符串,不需要修改任何Java代码,直接用Thymeleaf内置的temporals工具类完成格式化即可:
<th:block th:each="holiday : ${holidays}"> <!-- 直接对LocalDateTime类型的updated字段做格式化 --> <p th:text="${#temporals.format(holiday.updated, 'dd-MM-yyyy HH:mm')}"></p> </th:block>
Spring Boot 2.x以上版本的spring-boot-starter-thymeleaf默认已经包含thymeleaf-extras-java8time依赖,无需额外引入即可直接使用该工具类。
内容的提问来源于stack exchange,提问作者Murilo de Melo Reis
相关产品推荐
相关产品推荐

