我想使用Java的预定义格式来格式化Instant
。我可以用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>
答案 0 :(得分:1)
是的,您可以在百里香叶中进行设置,但是它非常冗长...对我有用:
<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}}" />
答案 1 :(得分:0)
您可以简单地指定SHORT
作为格式。
<div th:text="${#temporals.format(work.indexTime, 'SHORT')}"></div>
来自the README:
/* * 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 */