Spring+Thymeleaf 3.0.9:如何结合I18n通过模型使用dates.format方法
嘿,我来帮你搞定Spring+Thymeleaf结合I18n的日期格式化问题!其实步骤很清晰,咱们一步步来:
实现国际化日期格式化的完整方案
1. 先确认国际化消息配置到位
首先得保证你的多语言配置文件里已经定义了对应语言的日期格式,比如:
messages.properties(默认语言,比如英文):date.format.pattern=yyyy-MM-dd HH:mm:ssmessages_zh_CN.properties(中文):date.format.pattern=yyyy年MM月dd日 HH:mm:ss
其他语言的配置文件以此类推,确保date.format.pattern键对应了正确的格式串。
2. 简化Controller代码(可选但推荐)
你之前把date.format.pattern这个国际化键放到Model里其实是多余的——Thymeleaf可以直接通过#{}语法读取国际化消息,所以删掉这行代码就行:
// 删掉这行,不需要把键传到视图 model.addAttribute("dateFormatPattern", "date.format.pattern");
3. 在Thymeleaf视图里完成格式化
遍历personas的时候,直接用#dates.format()函数,第一个参数是实体的日期属性(比如persona.birthDate,记得换成你自己的字段名),第二个参数用#{date.format.pattern}获取当前语言对应的格式串:
<tbody> <tr th:each="persona : ${personas}" > <td th:text="${personaStat.count}">###</td> <!-- 基础版日期格式化 --> <td th:text="${#dates.format(persona.birthDate, #{date.format.pattern})}">2020-01-01</td> <!-- 优化版:处理日期为null的情况,显示默认文本 --> <td th:text="${#dates.format(persona.birthDate, #{date.format.pattern}) ?: '无日期数据'}">2020-01-01</td> </tr> </tbody>
4. 额外提示:Java 8+新日期API适配
如果你的实体用的是LocalDate/LocalDateTime这类Java 8+的日期类型,要换成#temporals.format()函数(需要确保引入了Thymeleaf的Spring5整合依赖):
<td th:text="${#temporals.format(persona.localBirthDate, #{date.format.pattern})}">2020-01-01</td>
内容的提问来源于stack exchange,提问作者Manuel Jordan
相关产品推荐
相关产品推荐

