Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the difference in days between two ISO8601 dates with Freemarker?

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.

like image 481
BenLanc Avatar asked Dec 20 '22 19:12

BenLanc


1 Answers

If by difference in days you mean how many times 24 hours were elapsed between the two dates, then this expression does that (you need at least FreeMarker 2.3.17 for ?long to work like this):

(
  (
    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

A nicer approach is to implement the function in Java with implementing TemplateMethodModelEx. Templates can pull that in with <#assign distanceInDays = 'com.example.DistanceInDaysMethod'?new()> (put this into a commonly #include-d or #import-ed file) and then you can use it as distanceInDays(s1, s2).

like image 157
ddekany Avatar answered Mar 09 '23 01:03

ddekany