Search code examples
javaemaildateformattingstringtemplate

Format date in String Template email


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?


Solution

  • 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