如何移除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>
問題解決: