我想将即时时间转换为日期,但我收到此错误:
freemarker.template.TemplateException:预期的哈希值。 newDate评估为freemarker.template.SimpleDate
我在Java上这样做:
Date newDate = new Date();
Instant instant = Instant.now();
webContext.put("newDate",new Date());
webContext.put("instant",instant);
我在Freemarker上这样做:
[#assign dateFormated = newDate.getAsDate().from(instant.ofEpochSecond(data.time.seconds))/]
谢谢
答案 0 :(得分:1)
FreeMarker模板通常不会公开Java API,也不允许您按名称访问Java类。我的意思是,在某些情况下确实如此,但一般不像newDate
在FreeMarker中没有子变量(如getAsDate
)。有些实用程序可以用来公开类的静态方法,例如:
TemplateHashModel staticModels
= ((BeansWrapper) configuration.getObjectWrapper())
.getStaticModels();
webContext.put("Date", staticModels.get("java.util.Date"));
webContext.put("Instant", staticModels.get("java.time.Instant"));
其中configuration
是您的freemarker.template.Configuration
单身人士。实际上,在配置FreeMarker的地方,您可以将Date
和Instant
添加到Configuration.setSharedVariable
的单身人士。
然后,您可以将Date.from(Instant.now())
写入模板,因为现在有一个Date
和Instant
变量,并且您已经明确告诉FreeMarker公开其静态方法。