Freemarker中的Java.time(Java 8)支持 [英] Java.time (Java 8) support in Freemarker
问题描述
有人知道在FreeMarker中支持新的java.time api的计划吗?或者是否有任何代码用于支持ZonedDateTime,LocalDateTime和Instant等类?
Does anybody know of any plans to support the new java.time api in FreeMarker? Or has anybody code laying around for supporting classes like ZonedDateTime, LocalDateTime and Instant?
我自己不难看出如何实现这些东西,但它实际上是一个相当大的任务。
Its not hard to see how to implement these things myself, but it is actually a rather big task.
推荐答案
我们假设你想要格式化新的日期/时间对象
Let's assume that you want format new date/time objects
-
创建自定义方法:
Create custom method:
public static class FormatDateTimeMethodModel
implements TemplateMethodModelEx {
public Object exec(List args) throws TemplateModelException {
if (args.size() != 2) {
throw new TemplateModelException("Wrong arguments");
}
TemporalAccessor time = (TemporalAccessor) ((StringModel) args.get(0)).getWrappedObject();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(((SimpleScalar) args.get(1)).getAsString());
return formatter.format(time);
}
}
将此方法放入模板模型中:
Put this method into template model:
templateModel.put(formatDateTime,new FormatDateTimeMethodModel());
templateModel.put("formatDateTime", new FormatDateTimeMethodModel());
并调用此方法模板内部:
And invoke this method inside of template:
$ {formatDateTime(MY_DATE,'HH:mm')}
${formatDateTime(MY_DATE, 'HH:mm')}
这篇关于Freemarker中的Java.time(Java 8)支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!