«Back to Home

Core Java

Topics

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
  1. import java.text.DateFormat;  
  2. import java.util.*;  
  3. public class DateFormatExample {  
  4.     static void printDate(Locale locale) {  
  5.         DateFormat f = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);  
  6.         Date cDate = new Date();  
  7.         String date = f.format(cDate);  
  8.         System.out.println(date + " " + locale);  
  9.     }  
  10.     public static void main(String[] args) {  
  11.         printDate(Locale.UK);  
  12.         printDate(Locale.US);  
  13.     }  
  14. }  
2

Output

3

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.