Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java.time (Java 8) support in Freemarker

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.

like image 674
Jakob Vad Nielsen Avatar asked Aug 18 '15 03:08

Jakob Vad Nielsen


2 Answers

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')}

like image 154
jnr Avatar answered Sep 23 '22 06:09

jnr


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.

like image 20
ddekany Avatar answered Sep 19 '22 06:09

ddekany