Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a placeholder in a String with a SimpleDateFormat Pattern

In a given String like this

".../uploads/${customer}/${dateTime('yyyyMMdd')}/report.pdf"

I need to replace a customer and a yyyyMMdd timestamp.

To replace the customer placeholder, I could use the StrSubstitutor from Apache Commons. But how to replace the SimpleDateFormat? We are running in a Spring enviourment, so maybe Spring EL is an option?

The markup for the placeholders is not fixed, it is ok if another library needs syntactical changes.

This small tests shows the problem:

SimpleDateFormat            formatter   = new SimpleDateFormat("yyyyMMdd");

String                      template    = ".../uploads/${customer}/${dateTime('yyyyMMdd')}/report.pdf";

@Test
public void shouldResolvePlaceholder()
{
    final Map<String, String> model = new HashMap<String, String>();
    model.put("customer", "Mr. Foobar");

    final String filledTemplate = StrSubstitutor.replace(this.template, model);

    assertEquals(".../uploads/Mr. Foobar/" + this.formatter.format(new Date()) + "/report.pdf", filledTemplate);
}
like image 732
d0x Avatar asked May 08 '13 08:05

d0x


1 Answers

Why don't you use MessageFormat instead?

String result = MessageFormat.format(".../uploads/{0}/{1,date,yyyyMMdd}/report.pdf", customer, date);

Or with String.format

String result = String.format(".../uploads/%1$s/%2$tY%2$tm%2$td/report.pdf", customer, date);
like image 81
NilsH Avatar answered Oct 14 '22 06:10

NilsH