在 Thymeleaf 中使用 DateFormat.SHORT

我想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>


慕桂英4014372
浏览 148回答 2
2回答

倚天杖

是的,你可以在 thymeleaf 中设置它,但它非常冗长......这对我有用:<th:block th:with="clazz=${T(java.time.format.DateTimeFormatter)},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style=${T(java.time.format.FormatStyle).SHORT},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; zone=${T(java.time.ZoneId).systemDefault()},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formatter=${clazz.ofLocalizedDateTime(style).withLocale(#locale).withZone(zone)}">&nbsp; &nbsp; <span th:text="${formatter.format(work.indexTime)}" /></th:block>您还可以添加一个从 Instant 到 String 的默认转换器,并在输出 Instant 时使用双括号语法:语境:public class Context extends WebMvcConfigurerAdapter {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void addFormatters(FormatterRegistry r) {&nbsp; &nbsp; &nbsp; &nbsp; DateTimeFormatter dateFormatter = DateTimeFormatter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ofLocalizedDateTime(FormatStyle.SHORT)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withLocale(LocaleContextHolder.getLocale())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withZone(ZoneId.systemDefault());&nbsp; &nbsp; &nbsp; &nbsp; r.addConverter(new Converter<Instant, String>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public String convert(Instant s) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return s != null ? dateFormatter.format(s) : "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}HTML:<div th:text="${{work.indexTime}}" />

繁花不似锦

您可以简单地指定SHORT为格式。<div&nbsp;th:text="${#temporals.format(work.indexTime,&nbsp;'SHORT')}"></div>从自述文件:/* &nbsp;*&nbsp;Format&nbsp;date&nbsp;with&nbsp;the&nbsp;specified&nbsp;pattern &nbsp;*&nbsp;SHORT,&nbsp;MEDIUM,&nbsp;LONG&nbsp;and&nbsp;FULL&nbsp;can&nbsp;also&nbsp;be&nbsp;specified&nbsp;to&nbsp;used&nbsp;the&nbsp;default&nbsp;java.time.format.FormatStyle&nbsp;patterns &nbsp;*&nbsp;Also&nbsp;works&nbsp;with&nbsp;arrays,&nbsp;lists&nbsp;or&nbsp;sets &nbsp;*/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java