Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Gerard Avatar asked Apr 28 '10 10:04

Gerard


People also ask

What is string date/time format?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.

What is mmm dd yyyy format?

MMM/DD/YYYY. Three-letter abbreviation of the month, separator, two-digit day, separator, four-digit year (example: JUL/25/2003) YY/DDD. Last two digits of year, separator, three-digit Julian day (example: 99/349) DDD/YY.


2 Answers

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

like image 109
Genius Avatar answered Oct 02 '22 13:10

Genius


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();
like image 24
BenM Avatar answered Oct 02 '22 13:10

BenM