英文:
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("%02d:%02d:%02d", hours, minutes, seconds)
: String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis);
}
我还需要在 Freemarker 中呈现 Duration。是否可以在 Freemarker 中使用相同的方法?
英文:
I have a java Duration object that should be formatted as hh:mm:ss
in xml.
<Duration>${duration}</Duration>
But it is rendered with the standard format.
<Duration>PT30S</Duration>
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("%02d:%02d:%02d", hours, minutes, seconds)
: String.format("%02d:%02d:%02d.%03d", 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论