Format date in String Template email

杀马特。学长 韩版系。学妹 提交于 2019-12-05 05:27:35

Use additional renderers like this:

internal class AdvancedDateTimeRenderer : IAttributeRenderer
{
    public string ToString(object o)
    {
        return ToString(o, null);
    }

    public string ToString(object o, string formatName)
    {
        if (o == null)
            return null;

        if (string.IsNullOrEmpty(formatName))
            return o.ToString();

        DateTime dt = Convert.ToDateTime(o);

        return string.Format("{0:" + formatName + "}", dt);
    }
}

and then add this to your StringTemplate such as:

var stg = new StringTemplateGroup("Templates", path);
stg.RegisterAttributeRenderer(typeof(DateTime), new AdvancedDateTimeRenderer());

then in st file:

$YourDateVariable; format="dd/mm/yyyy"$

it should work

Here is a basic Java example, see StringTemplate documentation on Object Rendering for more information.

StringTemplate st = new StringTemplate("now = $now$");
st.setAttribute("now", new Date());
st.registerRenderer(Date.class, new AttributeRenderer(){
    public String toString(Object date) {
        SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
        return f.format((Date) date);
    }
});
st.toString();

StringTemplate 4 includes a DateRenderer class.

My example below is a modified version of the NumberRenderer on the documentation on Renderers in Java

String template =
    "foo(right_now) ::= << <right_now; format=\"full\"> >>\n";


STGroup g = new STGroupString(template);
g.registerRenderer(Date.class, new DateRenderer());
ST st = group.getInstanceOf("foo");
st.add("right_now", new Date()); 
String result = st.render();

The provided options for format map as such:

  • "short" => DateFormat.SHORT (default)
  • "medium" => DateFormat.MEDIUM
  • "long" => DateFormat.LONG
  • "full" => DateFormat.FULL

Or, you can use a custom format like so:

foo(right_now) ::= << <right_now; format="MM/dd/yyyy"> >>

You can see these options and other details on the DateRenderer Java source here

one very important fact while setting date format is to use "MM" instead of "mm" for month. "mm" is meant to be used for minutes. Using "mm" instead of "MM" very generally introduces bugs difficult to find.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!