Saturday, September 7, 2013

DateFormat

DateFormat is a useful class in Java to format, date, time, or both.  In general, when formatting a date, time, or both, you don't need to create the date formatter object directly from the DateFormat class. Instead, the date, time, and both formatter objects can be obtained by calling the getDateInstance(int style), getTimeInstance(int style), and getDateTimeInstance(int style) methods respectivly.

For example, the code fragment below format the current date and time as a short date.
DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT);
Date d=new Date();
String date=df.format(d);
System.out.println(date);

The code fragment below formats the current time as a long time.
DateFormat df=DateFormat.getTimeInstance(DateFormat.LONG);
Date d=new Date();
String time=df.format(d);
System.out.println(time);

The two code fragments above format current date and time in the default locale. A locale represents a geographical, political, and cultural region. You can format date, time, and both for a specific locale by calling the getDateInstance(int style, Locale lo), getTimeInstance(int style,Locale lo), and getDateTimeInstance(int style, Locale lo) methods respectively. The code below format the current date as a short local UK date.

DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT,Locale.UK);
Date d=new Date();
String ukdate=df.format(d);
System.out.println(ukdate);

The table below shows the countries and their locale constants that can be used in formatting date value for specific countries.

CountryLocale Constant
CanadaLocale.CANDA
ChinaLocale.CHINA
GermanyLocale.GERMANY
ItalyLocale.ITLAY
JapanLocale.JAPAN
KoreaLocale.KOREA
TaiwanLocale.TAIWAN
United KingdomLocale.UK
United StatesLocale.US


Besides formatting date, time, or both you can use the DateFormat to convert or parse a string presenting date, time, and both to date, time, and both objects that can be used later in Java programs. The code below converts the string "08/09/2013" to date object.

DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT);
String sdate="08/09/2013";
try {
Date mydate=df.parse(sdate);
System.out.println(mydate);
} catch (ParseException e) {
e.printStackTrace();
}

If you want to format a date to match your own pattern, you can use the SimpleDateFormat class. It is a sub-class of the DateFormat class. By using the SimpleDateFormat class you can construct a date formatter object to match your pattern. For example, you can format the current date to display as a form of dd-MM-yyyy. The code below is an example.

DateFormat df=new SimpleDateFormat("dd-MM-yyyy");
String mydate=df.format(new Date());
System.out.println(mydate);

No comments:

Post a Comment