Internationalize Your Dates

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);		System.out.println(df.format(date));		df = DateFormat.getDateInstance(DateFormat.MEDIUM);		System.out.println(df.format(date));		df = DateFormat.getDateInstance(DateFormat.LONG);		System.out.println(df.format(date));		df = DateFormat.getDateInstance(DateFormat.FULL);		System.out.println(df.format(date));	}  //  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:

 3/26/9926-Mar-99March 26, 1999Friday, 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.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist