首页 > 解决方案 > 如何在 thymeleaf 中为输入和人类可读的文本输出使用不同的日期/时间格式

问题描述

我正在使用 Spring Boot 和 Thymeleaf。

对于 html 表单日期输入字段,我必须使用 2019-10-27 日期格式。对于人类可读的文本,我更喜欢使用适合区域设置的文本,例如 27.10.2019 或 10/27/2019。

Spring Boot 和 Thymeleaf 可以很容易地指定@DateTimeFormat和自动提取它th:field等等。在这里,我指定了技术格式,否则我的表单既不会呈现也不会正确提交。

有没有办法让 Thymeleaf 或 Spring 在其他场合使用不同的格式?我知道我可以做到 ${#temporals.format(period.end, #messages.msg('formats.readable.date.month'))},但是有没有办法以某种方式注册该东西并使其可用于自动转换?

标签: spring-bootinternationalizationthymeleaf

解决方案


您还可以使用一个WebDataBinder

@InitBinder
public void initBinder(WebDataBinder binder, final Locale locale) {
    String dateFormat = "MM/dd/yyyy";
    if(locale.getLanguage.equals("ar")){
        dateFormat = "dd-MM-yyyy";
    }
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}

推荐阅读