views:

266

answers:

3

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?

+3  A: 

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

Genius
Excellent! Thank you!
Gearóid
A: 

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.

Deep
A: 

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