4

I have an object in Freemarker which has dates in ISO8601 format (e.g. 2012-02-01T13:01:02+0000), how would I go about working out the difference in days between it and now?

In other non-Java scenarios I'd reformat it as a unix timestamp and do the maths (like the distance_of_time_in_words functions in RoR or Symfony), however as far as I can see, Freemarker is unable to turn a ISO8601 timestamp into unix timestamp.

And yes, I realise the template layer probably isn't the right place to be doing this kind of thing, but needs must etc.

4

1 回答 1

11

如果用天数来表示两个日期之间经过了多少次 24 小时,那么这个表达式就是这样做的(您至少需要 FreeMarker 2.3.17?long才能像这样工作):

(
  (
    s2?datetime("yyyy-MM-dd'T'HH:mm:ssZ")?long
    - s1?datetime("yyyy-MM-dd'T'HH:mm:ssZ")?long
  ) / (1000 * 60 * 60 * 24)
)?int

更好的方法是在 Java 中使用 implementation 来实现该功能TemplateMethodModelEx。模板可以将其拉入<#assign distanceInDays = 'com.example.DistanceInDaysMethod'?new()>(将其放入通常的#include-d 或#import-ed 文件中),然后您可以将其用作distanceInDays(s1, s2).

于 2012-07-10T17:28:54.257 回答