案例:在freemarker中直接比较两个时间
设定当前时间(在页面直接用${datetime("yyyy")}取得当前时间):
/**
*类说明
*@author ^_^
*@version 1.0 创建时间: May 22, 2010 11:24:27 AM
**/
public class DatetimeFreemarkerModel implements TemplateMethodModel {
private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 根据传入的日期时间格式,在页面上直接取得当前时间的格式化结果
* 如果格式为空或者错误,将返回yyyy-MM-dd HH:mm:ss
* 页面调用${datetime("yyyy")}/${datetime('yyyy')}
* @see com.yourcompany.ExtendedFreemarkerManager#createConfiguration
*
*/
@SuppressWarnings("unchecked")
public Object exec(List args) throws TemplateModelException {
Date date = new Date();
String pattern = args.get(0).toString();
try {
return new SimpleDateFormat(pattern).format(date);
} catch (RuntimeException e) {
return new SimpleDateFormat(DEFAULT_PATTERN).format(date);
}
}
}
然后比较两个时间的model:
/**
*类说明
*@author ^_^
*@version 1.0 创建时间: May 22, 2010 11:14:44 AM
**/
**/public class Compare2DateFreemarkerModel implements TemplateMethodModel {
@SuppressWarnings("unchecked")
public Object exec(List list) throws TemplateModelException {
if (list == null || list.size() != 2) {
throw new TemplateModelException("请输入两个日期");
}
Object timeOne = list.get(0);
Object timeTwo = list.get(1);
Date dateOne;
Date dateTwo;
if (timeOne instanceof String) {
dateOne = DateUtil.getDateFromString(timeOne.toString());
} else {
dateOne = (Date) timeOne;
}
if (timeTwo instanceof String) {
dateTwo = DateUtil.getDateFromString(timeTwo.toString());
} else {
dateTwo = (Date) timeOne;
}
if(dateOne.getTime()-dateTwo.getTime()>=0){
return true;
}else{
return false;
}
}
}
加入模板
/**
*类说明
*@author ^_^
*@version 1.0 创建时间: May 22, 2010 11:18:44 AM
**/
public class ExtendedFreemarkerManager extends FreemarkerManager {
@Override
protected Configuration createConfiguration(ServletContext servletContext)
throws TemplateException {
Configuration configuration = super.createConfiguration(servletContext);
//获得当前时间
configuration.setSharedVariable("dateTime", new DatetimeFreemarkerModel() );
//是否大于后者时间
configuration.setSharedVariable("isGltDate", new Compare2DateFreemarkerModel());
return configuration;
}
}
然后在struts.xml里添加
<constant name="struts.freemarker.manager.classname" value="com.hongwei.domi.util.ExtendedFreemarkerManager" />
最后在页面进行比较:
<#if isGltDate(dateTime("yyyy-MM-dd HH:mm"),endTime?string("yyyy-MM-dd HH:mm"))>
<span class="red12">您计较的报告超时了</span>
<#else>