Search code examples
javafreemarker

How to compare time in freemarker?


In Freemarker, I can use .now?time to get the current time, but how do I compare that to another time?

For example, how would I properly test if the current time is between 8:00 AM and 5:00 PM?

<#if .now?time gte (?) && .now?time lte (?)>
  //do something
<#/if>

I don't know what to put in the (?) because I'm not sure how to create date scalars in Freemarker.


Solution

  • Although you can compare two java.util.Date-s as far as they are both of the same kind (like both are time-only values), then it's up to you to ensure that the internal representations are consistent (like a time-only value is in the epoch-day VS on some other day). Thus it's mostly meant to be used for comparing date-time values (timestamps) where no such issue exists. So, since you know that you want an epoch-based time, you could do the following hack:

    <#assign nowTime = .now?time?string.iso?time.iso>
    

    Now it's correctly comparable with "8:00:00 AM"?time, however, I recommend using ISO format, because the locale-specific format is kind of fragile (like if you change locale, it won't work): '08:00:00'?time.iso. Note that for this you need at least FreeMarker 2.3.21.