在Freemarker中格式化日期,说“今天”,“昨天”等

时间:2010-12-07 20:16:51

标签: date format freemarker

freemarker中是否有办法比较日期以测试日期是今天还是昨天......或者我是否必须用Java编写代码来进行这些测试?

我基本上想要这样做:

<#------------------------------------------------------------------------------
 formatDate
------------------------------------------------------------------------------->
<#macro formatDate date showTime=true>
    <#if date??>
        <span class="Date">
            <#if date?is_today>
                Today
            <#elseif date?is_yesterday>
                Yesterday
            <#else>
                ${date?date}
            </#if>
        </span>
        <#if showTime>
            <span class="Time">${date?time}</span>
        </#if>
    </#if>
</#macro>

编辑:我最好的猜测是将“今天”和“昨天”传递给使用此功能的页面的模型,然后将日期值与这两个对象进行比较。模型。我没有选择,但我不想为每个使用此宏的页面执行此操作。还有其他更好的选择吗?

<#if date??>
    <span class="Date">
        <#if date?date?string.short == today?date?string.short>
            Today
        <#elseif date?date?string.short == yesterday?date?string.short>
            Yesterday
        <#else>
            ${date?date}
        </#if>
    </span>
    <#if showTime>
        <span class="Time">${date?time}</span>
    </#if>
</#if>

4 个答案:

答案 0 :(得分:10)

由于问题很老,我猜问题就消失了,但无论如何,我只是这样做了:

<#assign diff = (mydate?long / 86400000)?round - (.now?long / 86400000)?round />

。现在是一个构建,86400是每个程序员可能知道的常量,如果你不被丑陋的外观推迟,这给你一个整数差异天。今天是0,昨天是-1等。

如果你想让?is_today工作,可以通过实现如下所述的TemplateDirectiveModel来扩展freemarker语言:

http://freemarker.sourceforge.net/docs/pgui_datamodel_directive.html

但我还不知道如何将它实际添加到可用选项中?...表示法: - )

答案 1 :(得分:2)

1。使用以下方法创建实用程序类:

import org.joda.time.format.*;
...
public class StringAndDateUtils {

    public static String yesterdayOrToday(String date) {
        DateTime dateTime = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(date);
        DateTime today = new DateTime();
        DateTime yesterday = today.minusDays(1);

        if (dateTime.toLocalDate().equals(today.toLocalDate())) {
            return "Today " ;
        } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
            return "Yesterday " ;
        } else {
            return date;
        }
    }
}

2。在您的控制器中,将Class添加到您的模型中:

modelMap.addAttribute("StringAndDateUtils", new StringAndDateUtils());

3。在.FTL页面上使用如下方法:

<#assign date = realDateObject?string("MM/dd/yyyy")/>  
${StringAndDateUtils.yesterdayOrToday(date)}

答案 2 :(得分:1)

您可以将字符串转换为int(注意翻转!)并按照比较进行比较 http://sourceforge.net/projects/freemarker/forums/forum/2345/topic/3027925?message=6479650

如果添加额外数字(如毫秒),请注意不要超过最大int值。

(来自上述链接)

[#assign  Adate = myDateA?string("yyyyMMdd")?number?int ]
[#assign  Atime = myDateA?string("HHmmss")?number?int ]
[#assign  Bdate = myDateB?string("yyyyMMdd")?number?int ]
[#assign  Btime = myDateB?string("HHmmss")?number?int ]

我所做的是创建一个TemplateMethodModel来比较日期(注意:df是一个带有时区的自定义线程安全SimpleDateFormatter):

public BooleanModel exec(List args) throws TemplateModelException {
    int argcnt = args.size();

    if (argcnt != 3) {
        throw new TemplateModelException("Wrong arguments.  Use \"exec(Date?string(\"yyyyMMddHHmmss\"), " +
                "CompareString, Date?string(\"yyyyMMddHHmmss\"))\"," +
                " where CompareString is < = > ");
    }

    String firstDate = (String) args.get(0);
    String compareString = (String) args.get(1);
    String secondDate = (String) args.get(2);

    if (null == firstDate || null == secondDate || null == compareString ||
             compareString.length() != 1) {
        throw new TemplateModelException("Wrong arguments.  Use \"exec(Date?string(\"yyyyMMddHHmmss\"), " +
                "CompareString, Date?string(\"yyyyMMddHHmmss\"))\"," +
                " where CompareString is < = > ");
    }

    Date first = null;
    Date second = null;
    try {
        first = df.parse(firstDate);
        second = df.parse(secondDate);
    } catch (ParseException e) {
        throw new TemplateModelException("Wrong arguments.  Use \"exec(Date?string(\"yyyyMMddHHmmss\"), " +
                "CompareString, Date?string(\"yyyyMMddHHmmss\"))\"," +
                " where CompareString is < = > ");
    }

    if ("<".equals(compareString)) {
        return new BooleanModel(first.before(second), BeansWrapper.getDefaultInstance());
    }
    else if ("=".equals(compareString)) {
        return new BooleanModel(first.equals(second), BeansWrapper.getDefaultInstance());           
    }
    else if (">".equals(compareString)) {
        return new BooleanModel(first.after(second), BeansWrapper.getDefaultInstance());            
    }

    return new BooleanModel(Boolean.FALSE, BeansWrapper.getDefaultInstance());

}

在模板中,我将其称为:

[#if compareDate(now?string("yyyyMMddHHmmss"),"<", program.resStartDateTime?string("yyyyMMddHHmmss"))]

仅供参考,“now”是在模板处理之前添加的DateModel对象。

model.put("now", new DateModel(new Date(), BeansWrapper.getDefaultInstance()));

通过将解析字符串作为参数传递并在执行时创建日期格式化程序,可以使TemplateMethodModel更加通用。

答案 3 :(得分:0)

$ {houradd(date,24)?string(“yyyy-MM-dd HH:mm:ss”)}

$ {houradd(date,-24)?string(“yyyy-MM-dd HH:mm:ss”)}

$ {dayadd(date,1)?string(“yyyy-MM-dd HH:mm:ss”)}