为了账号安全,请及时绑定邮箱和手机立即绑定

在 Thymeleaf 中使用 DateFormat.SHORT

在 Thymeleaf 中使用 DateFormat.SHORT

慕桂英4014372 2021-09-29 10:08:08
我想Instant使用 Java 的预定义格式来格式化。我可以在 Java 中做到这一点:DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, request.getLocale());// this will hopefully format a Date to 12.09.2018 02:10我希望使用我的Instant类型在 Thymeleaf 中完成此操作:<div th:text="${#temporals.format(work.indexTime)}"></div><!-- this will print "2018-09-12T02:10:06Z" -->但是我怎么能告诉 Thymeleaf 使用这些DateFormat.SHORT设置呢?编辑:我目前的解决方法是这样的:控制器:DateTimeFormatter dateFormatter = DateTimeFormatter        .ofLocalizedDateTime(FormatStyle.SHORT)        .withLocale(request.getLocale())        .withZone(ZoneId.systemDefault());模板:<div th:text="${dateFormatter.format(work.indexTime)}"></div>
查看完整描述

2 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

是的,你可以在 thymeleaf 中设置它,但它非常冗长......这对我有用:


<th:block th:with="clazz=${T(java.time.format.DateTimeFormatter)},

          style=${T(java.time.format.FormatStyle).SHORT},

          zone=${T(java.time.ZoneId).systemDefault()},

          formatter=${clazz.ofLocalizedDateTime(style).withLocale(#locale).withZone(zone)}">

    <span th:text="${formatter.format(work.indexTime)}" />

</th:block>

您还可以添加一个从 Instant 到 String 的默认转换器,并在输出 Instant 时使用双括号语法:


语境:


public class Context extends WebMvcConfigurerAdapter {

    @Override

    public void addFormatters(FormatterRegistry r) {

        DateTimeFormatter dateFormatter = DateTimeFormatter

                .ofLocalizedDateTime(FormatStyle.SHORT)

                .withLocale(LocaleContextHolder.getLocale())

                .withZone(ZoneId.systemDefault());


        r.addConverter(new Converter<Instant, String>() {

            @Override

            public String convert(Instant s) {

                return s != null ? dateFormatter.format(s) : "";

            }

        });

    }

}

HTML:


<div th:text="${{work.indexTime}}" />


查看完整回答
反对 回复 2021-09-29
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

您可以简单地指定SHORT为格式。

<div th:text="${#temporals.format(work.indexTime, 'SHORT')}"></div>

自述文件

/*
 * Format date with the specified pattern
 * SHORT, MEDIUM, LONG and FULL can also be specified to used the default java.time.format.FormatStyle patterns
 * Also works with arrays, lists or sets
 */


查看完整回答
反对 回复 2021-09-29
  • 2 回答
  • 0 关注
  • 147 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信