Format date in String Template email

前提是你 提交于 2020-01-13 09:08:13

问题


I'm creating an email using String Template but when I print out a date, it prints out the full date (eg. Wed Apr 28 10:51:37 BST 2010). I'd like to print it out in the format dd/mm/yyyy but don't know how to format this in the .st file.

I can't modify the date individually (using java's simpleDateFormatter) because I iterate over a collection of objects with dates.

Is there a way to format the date in the .st email template?


回答1:


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




回答2:


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();



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2728623/format-date-in-string-template-email

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