Java Cookbook
Formating dates and times
Problem:
You want to format a date correctly for a locale.
Solution:
Formatting dates and times correctly for a locale can prove challenging, especially considering the variety of possibilities. Thankfully, Java provides a number of date formatting methods and classes. icu4j adds even more tools to the programmers toolbox.
To format a date you need to get an instance of the DateFormat class passing the locale in:
//Get a locale object. In this case we could also use the static constant Locale.FRENCH
Locale french = new Locale("fr");
//Get a DateFormat instance using the locale. We also specify a length.
//Possible length values are DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL
//To demonstrate we will get an example of each
int[] lengths = {DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL};
//Loop through the lengths. Get a DateFormat instance for each length and format a date
for(int x = 0; x < lengths.length; x++){
DateFormat df = DateFormat.getDateInstance(lengths[x], french);
System.out.println(df.format(new Date()));
}
The output:
29/11/08
29 nov. 2008
29 novembre 2008
samedi 29 novembre 2008
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search