Spring java8 LocalDatetime 格式化
如何移除LocalDateTime中的T
写如下的一个Controller:
@RestController
public class IndexController {
@RequestMapping(method = RequestMethod.GET, path = "/")
public Object hello() {
return LocalDateTime.now();
}
}
浏览器访问后,发现中间有个“T”,而且带毫秒,很别扭。
添加一个配置类重新定义格式,可解决:
@Configuration
public class LocalDateTimeConfig {
private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
@Bean
@Primary
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
另,注意不能直接调用LocalDateTime.toString
方法,因为该方法的定义为:
// LocalDateTime.java
@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
所以,如果RequesMapping
方法定义如下,则LocalDateTimeConfig
无法起到作用:
@RequestMapping(method = RequestMethod.GET, path = "/hello2")
public String hello2() {
return LocalDateTime.now().toString;
}
浏览器访问得到:
Model中如何解决
上述的自定义LocalDateTime
配置对于Thymeleaf
中的字段无法生效。
有如下Controller:
@Controller
public class StudentController {
@RequestMapping(method = RequestMethod.GET, path = "/student")
public Object show(Model model) {
Student student = new Student("wang", LocalDateTime.now());
model.addAttribute("student", student);
return "student-info-page";
}
}
student-info-page.html
如下:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="${student}"></p>
</body>
</html>
浏览器显示如下:
可见,是直接调用了LocalDateTime.toString
方法。
如何解决呢?
第一种尝试:在Student
类的birth
字段添加@JsonFormat
注解:
@Data
@AllArgsConstructor
public class Student {
private String name;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime birth;
}
经测试,无效。
第二种尝试:在Thymeleaf
中显示时进行格式化。修改html文件:
<p th:text="'name=' + ${student.getName()}
+ '; birth='
+ ${#temporals.format(student.getBirth(),'yyyy-MM-dd HH:mm:ss')}">
</p>
问题解决: