|Home > Guides > Core Developers Guide > Formatting Dates and Numbers|
Struts2 supports localization (l10n) aware formatting of dates, times and numbers very easily, utilizing Java's built-in date formatting features.
As seen in the Localization chapter, it is quite easy to define hierarchical resource bundles with Struts2, giving the developer the opportunity to define locale dependent message formats. This is the entry point to define the needed date, time and number formats. Your default properties could contain the following generic formats:
An appropriate en_US format definition extension could look like this:
In parallel, you could add the following to your de_DE bundle:
Read more on how to define message formats in Sun's Java API docs for MessageFormat.
Now that we have our formats set up, it is quite easy to use them in our views.
Given you had a Float value myMoneyValue, accessible through the getter getMyMoneyValue in your action, the following code would print out localized representation of the value as a currency amount, using the format.money message format defined above with a s:text tag:
The (first) parameter defines the value which is to replace the '0' placeholder in the defined message format.
Another example, formatting a date value:
Placing a textfield in a form like this
to input a number, one might have noticed that the number is always shown in the Java default number format. Not only that this is not "nice", if you are in a non-en locale, it will also cause trouble when submitting the form since type conversion is locale aware. The solution is to again use the message formats as defined above, by using the getText Method of ActionSupport:
This maps to the method signature getText( String key, Object params ) in ActionSupport.
A new method getFormatted was added to ActionSupport (which can be implemented in your base action) to support formatting and conversion errors with I10N.
You can place a code like below
to get support for I10N and also to support conversion errors.