Spring java8 LocalDatetime 格式化

如何移除LocalDateTime中的T

寫如下的一個Controller:

@RestController
public class IndexController {

    @RequestMapping(method = RequestMethod.GET, path = "/")
    public Object hello() {
        return LocalDateTime.now();
    }
}

瀏覽器訪問後,發現中間有個“T”,而且帶毫秒,很彆扭。

image-20200526141331992

添加一個配置類重新定義格式,可解決:

@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;
}

瀏覽器訪問得到:

image-20200526143852501

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>

瀏覽器顯示如下:

image-20200526144205890

可見,是直接調用了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>

問題解決:

image-20200526150640601

完整代碼:https://gitee.com/duanguyuan/LocalDateTimeTest

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章