Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Apr 6, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Internationalize Your Dates

Although the Gregorian calendar is used by most of the world, the specific way in which dates are formatted varies from one place to another. In the United States, for example, the most commonly used format is mm/dd/yy (or mm/dd/yyyy), where mm represents the month, dd represents the day of the month, and yy represent the last two digits of the year. However, in other countries, the dd/mm/yy format is often used instead. As a result, using a specific date format can cause an application to break when it is run by a user in a locale different from where the application was developed. Fortunately, Java provides an easy way to address this problem.

The java.text.DateFormat class provides static methods which return references to objects that are be used to format date values appropriately based on the user's locale. There are four different date formats supported for each locale: SHORT, MEDIUM, LONG, and FULL, with each successive format displaying a lengthier version of the date than the previous one. For example:

import java.text.*;
import java.util.*;

public class datetest {
	public static void main(String[] args) {
		DateFormat df;
		Date date = new Date();
		df = DateFormat.getDateInstance(DateFormat.SHORT);
		df = DateFormat.getDateInstance(DateFormat.MEDIUM);
		df = DateFormat.getDateInstance(DateFormat.LONG);
		df = DateFormat.getDateInstance(DateFormat.FULL);
	}  //  public static void main(String[] args)
}  //  public class datetest
Running this code on an appropriately configured machine in the United States on March 26, 1999 would display:
March 26, 1999
Friday, March 26, 1999
The DateFormat class also provides similar capabilities for displaying time values, as well as date and time combinations. These values are available through the getTimeInstance() and getDateTimeInstance() methods, respectively.
Brett Spell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date