当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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.

网友答案:

I read the source of freemarker 2.3.21 and found that current freemarker does not support comparing .now?time and time object such as "8:00:00 AM"?time.

That is because.now?time is internally treated as current time such as 2014-10-21 15:11:30, and "8:00:00 AM"?time is treated as 1970-01-01 08:00:00.

Therefore, <#if .now?time gte "8:00:00 AM"?time > is always true.

If you think it's a bug you may report to http://sourceforge.net/p/freemarker/bugs/ or send a question in freemarker's mailing list.

So the current workaround is to create the Date object and compare it in the java code.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: