注释@DateTimeFormat不适用于Spring Boot和Thymeleaf

时间:2018-09-26 17:07:49

标签: java date spring-boot thymeleaf date-formatting

我正在使用Springboot,Java和Thymeleaf。

public class DirectBind {

    @Column(columnDefinition = "date")
    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private LocalDate policyTermDateStart;

    @Column(columnDefinition = "date")
    @DateTimeFormat(pattern = "MM/dd/yyyy")
 ...
}

我的约会日期是yyyy-mm-dd。您知道我可以如何更改此代码/在何处实现代码,以便对其进行更改。它在我的控制器中吗?这是我发送获取用户输入日期的表单时的代码

@RequestMapping(value = "/send")
public String send(Model model, @ModelAttribute(value = "directBind") DirectBind directBind) {
    List<String> businessAgencyList = directBind.getBusinessAgencyList();
    List<String> billTypeOptions = directBind.getBillTypeOptions();
    Mail mail = new Mail();
    mail.setFrom("no-reply@hgitservices.com");
    mail.setTo(new String[]{"stacief@hgitservices.com"});
    mail.setSubject("Oli Affiliate - AMS360 & PMA Data Checklist");
    Map<String, Object> mailModel = new HashMap<>();
    mail.setModel(mailModel);
    try {
        emailService.sendSimpleMessage(mail, directBind);
    } catch (Exception e) {
        e.printStackTrace();
        return ("redirect:/?sentMessageFail");
    }
    return ("redirect:/?sentMessage");
}

@RequestMapping(value = "/email")
public String email() {
    return "emailMessage";
}

2 个答案:

答案 0 :(得分:1)

让它可以使用#temporals!

<tr class="emailRow">
        <td colspan="1" class="dateRangeEnd" th:text="${#temporals.format(directBind.policyTermDateEnd, 'MM/dd/yyyy')}">
         </td>
</tr>

答案 1 :(得分:0)

您有两个独立的问题。我将回答标题中的那个。我还假设您是指@RestController的JSON的输出/输入。

Spring Boot使用Jackson作为默认设置。要使日期格式全局应用,您可以使用Spring配置来配置Jackson的对象映射器,例如:

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        setDateFormat(objectMapper);

        return objectMapper;
    }

    private static void setDateFormat(ObjectMapper mapper) {
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        df.setLenient(false); // not necessary but I would recommend
        mapper.setDateFormat(df);
    }

}

如果您需要使用其他格式,则可以使用注释覆盖每个字段的全局配置,但是:我无法让Jackson对象映射器服从Spring @DateTimeFormat注解。相反,它读取的注释类似于@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy")