简体   繁体   中英

Freemarker format integer as minutes and seconds

I have an integer value that represents a time span in seconds and I shall format it as minutes and seconds: Example: I have an integer durationInSeconds = 341 and want it to be displayed as 05:41 .

The only way I could find for formatting is formatting a date, but i don't have a date - I have an integer

This works:

${.now?date?string("mm:ss")}

It will output the current minutes and seconds, eg 46:50

This doesn't work:

${durationSeconds?date?string("mm:ss")}

It gives me a error:

Unparseable date: "341"

Is there an easy way to convert/format the integer value this way?

Numbers can be converted to date/time/datetime via ?number_to_date / ?number_to_time / ?number_to_datetime , but they are not what you want, as they interpret the input as milliseconds passed since the epoch, plus the formatting will count in your time zone. But you have a duration here, not an instant. Thus, you can simply do this:

${(durationSeconds / 60)?int}:${durationSeconds % 60}

Of course if you need this on multiple places, then you can define a #macro for this (then it will be like <@duration durationSeconds /> ), or define a custom number format for this (then it will be like ${durationSeconds?string.@duration} ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM