3.2.2.3.4. 代码中的日期和数字格式化示例
如果需要按照用户当前的 locale 格式化或者解析 BigDecimal 、 Integer 、 Long 、 Double 、 Boolean 或者 Date 类型,可以使用 DatatypeFormatter bean,示例:
@Inject
private DatatypeFormatter formatter;
void sample() {
String dateStr = formatter.formatDate(dateField.getValue());
// ...
}
下面是直接使用 Datatype 的例子。
-
日期格式化示例:
@Inject protected UserSessionSource userSessionSource; @Inject protected DatatypeRegistry datatypes; void sample() { Date date; // ... String dateStr = datatypes.getNN(Date.class).format(date, userSessionSource.getLocale()); // ... } -
在 Web 客户端格式化数字,显示最多 5 位小数示例:
com/sample/sales/web/messages_ru.propertiescoordinateFormat = #,##0.00000@Inject protected Messages messages; @Inject protected UserSessionSource userSessionSource; @Inject protected FormatStringsRegistry formatStringsRegistry; void sample() { String coordinateFormat = messages.getMainMessage("coordinateFormat"); FormatStrings formatStrings = formatStringsRegistry.getFormatStrings(userSessionSource.getLocale()); NumberFormat format = new DecimalFormat(coordinateFormat, formatStrings.getFormatSymbols()); String formattedValue = format.format(value); // ... }