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.
Country | Locale Constant |
---|---|
Canada | Locale.CANDA |
China | Locale.CHINA |
Germany | Locale.GERMANY |
Italy | Locale.ITLAY |
Japan | Locale.JAPAN |
Korea | Locale.KOREA |
Taiwan | Locale.TAIWAN |
United Kingdom | Locale.UK |
United States | Locale.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);
Thank you again for all the knowledge you hand out, Good post. I was very interested in the article; it's quite inspirational I should admit. I like visiting you site since I always come across attractive articles like this one. Great Job, I greatly am grateful for that. Do keep giving out! Regards.
ReplyDeleteMore hints : Custom essay writing service