Internationalize Date In Java
Internationalize Date
The format of the dates is different from one region to another region due to which we internationalize the dates. We can internationalize the date with the help of getDateInstance() method of the DateFormat class. It receives the locale object as a parameter and returns the object of the DateFormat class.
Methods of DateFormat class
There are two methods of the DateFormat class for internationalizing the dates, given below.
public static DateFormat getDateInstance(int style, Locale locale)
This method is used to return the object of the DateFormat class for the specific style and locale. The style can be DEFAULT, SHORT, LONG etc.
public String format(Date date)
This method is used to return the formatted and localized date as a string.
Let’s see an example of internationalizing the date.
Code
- import java.text.DateFormat;
- import java.util.*;
- public class DateFormatExample {
- static void printDate(Locale locale) {
- DateFormat f = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
- Date cDate = new Date();
- String date = f.format(cDate);
- System.out.println(date + " " + locale);
- }
- public static void main(String[] args) {
- printDate(Locale.UK);
- printDate(Locale.US);
- }
- }
Output
In the example, mentioned above, we display the date, according to the different locale such as UK and US. For this reason, we have created the printDate() method, which receives Locale object as an instance and the format() method of the DateFormat class receives the date object and gives the formatted and localized date as a string.
Summary
Thus, we learnt that we can internationalize the date with the help of getDateInstance() method of the DateFormat class and also learnt how to internationalize the date in Java.