Locale-Aware Time Formatting
While SimpleDateFormat is useful for custom patterns, it does not automatically adapt to regional conventions. The DateFormat class resolves this by offering built-in locale support, adjusting string representations dynamically based on the user's language and region settings.
Package Availability
The DateFormat class exists within three distinct packages:
java.textandroid.text.formatandroid.icu.text
This overview focuses on the java.text and android.text.format implementations.
Implementing java.text.DateFormat
The primary factory methods are getDateInstance() and getDateTimeInstance(), which accept integer style constants to dictate the verbosity of the output. The system handles the localized string assembly automatically.
Available Style Constants
DateFormat.FULL: Provides the most detailed representation, including the weekday.DateFormat.LONG: Offers detailed information without the weekday.DateFormat.MEDIUM: Displays a standard, medium-length format.DateFormat.SHORT: Presents a completely numeric, compact format.DateFormat.DEFAULT: Defaults to theMEDIUMstyle.
Formatting the Date Only
long currentTimestamp = System.currentTimeMillis();
Date currentDate = new Date(currentTimestamp);
int[] styleConfigs = {DateFormat.FULL, DateFormat.LONG, DateFormat.MEDIUM, DateFormat.SHORT, DateFormat.DEFAULT};
for (int config : styleConfigs) {
String formattedResult = DateFormat.getDateInstance(config).format(currentDate);
System.out.println("Style constant " + config + " yields: " + formattedResult);
}Formatting Both Date and Time
long epochMillis = System.currentTimeMillis();
Date presentTime = new Date(epochMillis);
Map<String, Integer> styleMap = new LinkedHashMap<>();
styleMap.put("FULL", DateFormat.FULL);
styleMap.put("LONG", DateFormat.LONG);
styleMap.put("MEDIUM", DateFormat.MEDIUM);
styleMap.put("SHORT", DateFormat.SHORT);
styleMap.put("DEFAULT", DateFormat.DEFAULT);
for (Map.Entry<String, Integer> entry : styleMap.entrySet()) {
String formattedDateTime = DateFormat.getDateTimeInstance(entry.getValue(), entry.getValue()).format(presentTime);
System.out.println(entry.getKey() + " representation: " + formattedDateTime);
}