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

posted @ 2020-05-26 15:27  duanguyuan  阅读(1962)  评论(0编辑  收藏  举报