Richie Richie - 4 months ago 30
Java Question

Format a date using the %f %s (I think Java 7 formatter) type notation

I am using Spring Batch to output my domain object to a CSV file. To do this I am making use of a

FormatterLineAggregator
. It uses the
%s %f
type formats.

See below.

FormatterLineAggregator<MasterList> lineAggregator = new FormatterLineAggregator<>();
lineAggregator.setFormat("%s,%.2f,%.2f,%s,%s,%s,%s,%s,%s,%s,%s");


This code is formatting my object into this line in my CSV.

A,100.00,100.00,Country Road Shirt,Promotion Component Name A,wasnow,On Sale,100,100 / 1000,2016-07-24,2016-07-24


I am really unfamiliar with the
%s %f
notation.

I want my dates on the end of that line to look like
dd/mm/yyyy hh24:mi:ss
instead they are
yyyy-mm-dd
.

How can I do that using this notation?

Also does anyone know where I can find a reference explaining the syntax more?

Answer

You can use the below format to format your date.

%1$te/%<tm/%<tY %<tT

Here we reference arguments by position is to use the '<' ('\u003c') flag, which causes the argument for the previous format specifier to be re-used.

Example:

Formatter formatter = new Formatter(sb, Locale.US);
// Explicit argument indices may be used to re-order output.
formatter.format("%s,%.2f,%.2f,%s,%s,%s,%s,%d,%s,%10$te/%<tm/%<tY %<tT,%11$te/%<tm/%<tY %<tT","A",11.2,12.3,"Country Road Shirt","Promotion Component Name A","wasnow","On Sale",100,"100 / 1000",new Date(),new Date());
System.out.println(sb);

Output:

A,11.20,12.30,Country Road Shirt,Promotion Component Name A,wasnow,On Sale, 100,100 / 1000,25/07/2016 11:10:47,25/07/2016 11:10:47

Here is the code in ideone

For more information you can refer Java Doc Formatter