使用%f%s(我认为Java 7格式化程序)类型表示法格式化日期

时间:2016-07-24 12:44:21

标签: java spring spring-batch

我正在使用Spring Batch将我的域对象输出到CSV文件。要做到这一点,我正在使用FormatterLineAggregator。它使用%s %f类型格式。

见下文。

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

此代码将我的对象格式化为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

我对%s %f符号非常不熟悉。

我希望该行末尾的日期看起来像dd/mm/yyyy hh24:mi:ss,而不是yyyy-mm-dd

如何使用这种表示法来做到这一点?

也有人知道在哪里可以找到更多解释语法的参考资料吗?

1 个答案:

答案 0 :(得分:2)

自Java 1.5.0以来,存在

Formatter类。 您可以使用以下格式设置日期格式。

%te/%<tm/%<tY %<tT

'e'     Day of month, formatted as two digits, i.e. 1 - 31. 
'm'     Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13
'Y'     Year, formatted as at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
'T'     Time formatted for the 24-hour clock as "%tH:%tM:%tS". 

这里我们按位置引用的参数是使用'&lt;' ('\ u003c')标志,它导致重用前一格式说明符的参数。

示例:

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%s,%.2f,%.2f,%s,%s,%s,%s,%d,%s,%te/%<tm/%<tY %<tT,%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);

输出:

  

A,11.20,12.30,乡村公路衬衫,促销组件名称A,wasnow,On Sale,100,100 / 1000,25 / 07/2016 11:10:47,25 / 07/2016 11:10:47

以下是ideone

中的代码

有关详细信息,请参阅Java Doc Formatter