Java.time (Java 8) support in Freemarker

半世苍凉 提交于 2019-12-01 18:00:57

Let's assume that you want format new date/time objects

  1. 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);
        }
    }
    
  2. Put this method into template model:

    templateModel.put("formatDateTime", new FormatDateTimeMethodModel());

  3. And invoke this method inside of template:

    ${formatDateTime(MY_DATE, 'HH:mm')}

Nobody deals with that right now (2.3.24), though it's known to be missing. It probably won't be trivial to do properly, unless degrading Java 8 date/time types to java.util.Date-s when they are returned by TemplateDateModel is acceptable.

BTW, I have added this to http://freemarker.org/contribute.html, so that it won't be forgotten.

private static class CustomObjectWrapper extends DefaultObjectWrapper {
    @Override
    public TemplateModel wrap(Object obj) throws TemplateModelException {
        if (obj instanceof LocalDateTime) {
            Timestamp timestamp = Timestamp.valueOf((LocalDateTime) obj);
            return new SimpleDate(timestamp);
        }
        if (obj instanceof LocalDate) {
            Date date = Date.valueOf((LocalDate) obj);
            return new SimpleDate(date);
        }
        if (obj instanceof LocalTime) {
            Time time = Time.valueOf((LocalTime) obj);
            return new SimpleDate(time);
        }
        return super.wrap(obj);
    }
}


@Autowired
private freemarker.template.Configuration configuration;

configuration.setObjectWrapper(new CustomObjectWrapper());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!