什么是在Freemarker中格式化Duration对象的好方法?

huangapple go评论146阅读模式
英文:

What is a good way to format a Duration object in freemarker?

问题

我有一个 Java Duration 对象,应该以 `hh:mm:ss` 的格式在 xml 中进行格式化。

<Duration>${duration}</Duration>


但它以标准格式呈现。

<Duration>PT30S</Duration>


我有一个 Java 方法,可以格式化持续时间,目前用于 JSON 映射。

public static String format(Duration value) {
    long hours = value.toHours();
    int minutes = value.toMinutesPart();
    int seconds = value.toSecondsPart();
    int millis = value.toMillisPart();
    return millis == 0
        ? String.format(&quot;%02d:%02d:%02d&quot;, hours, minutes, seconds)
        : String.format(&quot;%02d:%02d:%02d.%03d&quot;, hours, minutes, seconds, millis);
}

我还需要在 Freemarker 中呈现 Duration。是否可以在 Freemarker 中使用相同的方法?
英文:

I have a java Duration object that should be formatted as hh:mm:ss in xml.

&lt;Duration&gt;${duration}&lt;/Duration&gt;

But it is rendered with the standard format.

&lt;Duration&gt;PT30S&lt;/Duration&gt;

I have a method in java that can format a duration and it is currently used for json mapping.

    public static String format(Duration value) {
        long hours = value.toHours();
        int minutes = value.toMinutesPart();
        int seconds = value.toSecondsPart();
        int millis = value.toMillisPart();
        return millis == 0
            ? String.format(&quot;%02d:%02d:%02d&quot;, hours, minutes, seconds)
            : String.format(&quot;%02d:%02d:%02d.%03d&quot;, hours, minutes, seconds, millis);
    }

I also need to render Duration in freemarker. Is it possible to use this same method in freemarker?

答案1

得分: 1

以下是已翻译的内容:

没有内置的格式化功能适用于任何Java 8时间类,截止到FreeMarker 2.3.32版本。(尽管有一个开发分支,其中包含半成品实现,但甚至那个版本也还未涉及Duration。)

当然,你可以在FreeMarker中调用静态实用方法。你必须将此值放入数据模型(模板上下文),并使用你喜欢的名称(在这种情况下是MyUtils)。代码如下:

((BeansWrapper) cfg.getObjectWrapper()).getStaticModels().get(MyUtils.class.getName())

其中,cfg 是FreeMarker的Configuration单例。

英文:

There's no built-in formatting for any of the Java 8 temporal classes as of FreeMarker 2.3.32. (Though there's a development branch with a semi-finished implementation, not even that addresses Duration yet.)

But, of course you can call static utility methods from FreeMarker. You have to put the value of this into the data-model (the template context), with the name you prefer (like MyUtils in this case) ((BeansWrapper) cfg.getObjectWrapper()).getStaticModels().get(MyUtils.class.getName()), where cfg is the FreeMarker Configuration singleton.

huangapple
  • 本文由 发表于 2023年8月11日 04:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76879015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定