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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With