首页 > 代码库 > Freemarker时间戳转日期

Freemarker时间戳转日期

需求:从第三方获取一个变量lastclock,里面值是1305575275540,一串时间戳,在页面用Freemarker将之转换成常见日期格式。

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public final class FreemarkUtils {
	private static Configuration cfg = new Configuration();
	private static String key="key";
	
	/**
	 * 根据模板返回Freemark渲染后的值
	 * @param name
	 * @param map
	 * @return Freemark渲染后的值
	 * @throws Exception
	 * @author chenqing
	 */
	public static String getTemplateValue(String name, Map<String, Object> map) throws Exception {
		StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
		stringTemplateLoader.putTemplate(key, name);
		cfg.setTemplateLoader(stringTemplateLoader);

		Template t = cfg.getTemplate(key);
		StringWriter out = new StringWriter();
		
		t.process(map, out);		
		return out.toString();
	}
	
	/**
	 * 直接返回Freemark渲染后的值
	 * @param name
	 * @return Freemark渲染后的值
	 * @throws Exception
	 */
	public static String getTemplateValue(String name) throws Exception {
		return getTemplateValue(name, new HashMap<String, Object>());
	}
		
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("lastclock", "1305575275540");
			String out = FreemarkUtils.getTemplateValue("${lastclock?number?number_to_datetime}", root);
			System.out.println(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}



上面的方法可以扩展,用于字符串输出的包装,不局限于web页。

Freemarker时间戳转日期