Formatting Date in String Template Letter

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

I cannot change the date separately (using java simpleDateFormatter) because I iterate over a set of objects with dates.

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

+7
java date email formatting stringtemplate
source share
4 answers

Use additional visualization tools as follows:

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, for example:

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

then in the st file:

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

he should work

+6
source share

The following is a basic Java example; see the StringTemplate documentation for rendering objects 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(); 
+2
source share

StringTemplate 4 includes the DateRenderer class.

My example below is a modified version of NumberRenderer in the Renderers documentation 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 options provided for the format map as such are:

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

Or you can use your own format:

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

You can see these options and other information about the Java source DateRenderer here.

+1
source share

one very important fact, and the date format is to use "MM" instead of "mm" for the month. "mm" is intended to be used within minutes. Using "mm" instead of "MM" very often introduces errors that are hard to find.

0
source share

All Articles