Spring Boot前端模板中显示时间${bo.createTime!}时如何把createTime转为年月日时分秒格式
时间: 2024-10-19 10:02:30 浏览: 49
在Spring Boot项目中,当你想要将createTime
字段转换为年月日时分秒的格式并显示在前端模板中,通常可以使用Thymeleaf模板引擎的内置函数或者自定义日期格式化。这里假设你正在使用的模板引擎是Thymeleaf,你可以这样做:
使用Thymeleaf内置函数:
<td th:text="${#temporals.format(bo.createTime, 'yyyy-MM-dd HH:mm:ss')}" />
这会将
createTime
字段按照指定的格式"yyyy-MM-dd HH:mm:ss"格式化。使用Java 8日期格式化 (如果你的
createTime
是LocalDateTime
或Instant
):String formattedTime = LocalDateTime.ofInstant(bo.createTime.toInstant(), ZoneId.systemDefault()) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); thymeleafContext.put("formattedCreateTime", formattedTime);
然后在HTML模板里引用变量
formattedCreateTime
:
<td th:text="${formattedCreateTime}" />
- 使用Spring EL表达式和日期转换器: 首先在Spring配置类中启用日期转换器,然后在模板中使用EL表达式:
@Bean
public MessageConverter dateTimeMessageConverter() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper() {{
registerModule(new JavaTimeModule());
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(formatter);
}});
return converter;
}
// 在模板中使用
<td th:text="${bo.createTime?string('yyyy-MM-dd HH:mm:ss')}" />
这里我们使用了Jackson库的定制化ObjectMapper
来格式化日期。
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)