DateFormat helps to format and parse dates for any locale . DateFormat has many methods for obtaining default date / time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include SHORT (23/07/11 ) , MEDIUM ( Jul 23, 2011 ), LONG (July 23, 2011 ) , FULL (Saturday, 23 July 2011 ). DateFormat has a method getDateInstance() which is used to get the normal date format for that country
To format a date in the current Locale,
dateFormatStr = DateFormat.getDateInstance().format(myDate);
To format a date for a different Locale, specify it in the call to getDateInstance().
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
The following code formats the current date into various different locales with different styles (SHORT, MEDIUM, LONG, FULL)
import java.util.*;
import java.text.*;
public class DateFormatLocale
{
public static void main(String args[])
{
Date today = new Date();
Locale[] locales ={Locale.CHINA, Locale.UK, Locale.GERMANY, Locale.FRANCE, Locale.US };
int[] fmt_styles={ DateFormat.SHORT,DateFormat.MEDIUM,DateFormat.LONG, DateFormat.FULL};
DateFormat format;
String[] fmt_style_str={ "SHORT", "MEDIUM", "LONG", "FULL"};
for (int i=0; i<locales.length;i++)
{
System.out.println("\n The date format for the country " + locales[i].getDisplayCountry() );
for (int j=0; j<fmt_styles.length;j++)
{
format = DateFormat.getDateInstance(fmt_styles[j], locales[i]);
System.out.println("\n " + fmt_style_str[j] + " is " + format.format(today));
}
}
String dateCurrentLocale = DateFormat.getDateInstance().format(today);
System.out.println("Date format for the current locale " + dateCurrentLocale);
}
}
Output of the Program:
java DateFormatLocale
The date format for the country China
SHORT is 7/23/11
MEDIUM is Jul 23, 2011
LONG is July 23, 2011
FULL is Saturday, July 23, 2011
The date format for the country United Kingd
SHORT is 23/07/11
MEDIUM is 23-Jul-2011
LONG is 23 July 2011
FULL is Saturday, 23 July 2011
The date format for the country Germany
SHORT is 23.07.11
MEDIUM is 23.07.2011
LONG is 23. Juli 2011
FULL is Samstag, 23. Juli 2011
....
......
0 comments:
Post a Comment