Java.time (Java 8) support in Freemarker

后端 未结 3 591
眼角桃花
眼角桃花 2021-01-18 02:28

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

3条回答
  •  攒了一身酷
    2021-01-18 03:03

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

提交回复
热议问题