Java Date Format for Locale

How can I find the DateFormat for a given Locale?


Solution 1:

DateFormat.getDateInstance(int,Locale)

For example:

import static java.text.DateFormat.*;

DateFormat f = getDateInstance(SHORT, Locale.ENGLISH);

Then you can use this object to format Dates:

String d = f.format(new Date());

If you actually want to know the underlying pattern (e.g. yyyy-MMM-dd) then, as you'll get a SimpleDateFormat object back:

SimpleDateFormat sf = (SimpleDateFormat) f;
String p1 = sf.toPattern();
String p2 = sf.toLocalizedPattern();

Solution 2:

tl;dr

DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                 .withLocale( Locale.CANADA_FRENCH );

java.time

The original date-time classes are now legacy and have been supplanted by the java.time classes.

The DateTimeFormatter has a simple way to localize automatically by Locale when generating a String to represent the date-time value. Specify a FormatStyle to indicate length of output (abbreviated or not).

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL );
f = f.withLocale( Locale.CANADA_FRENCH );

Get the current moment. Notice that Locale and time zone have nothing to do with each other. One determines presentation, the other adjusts into a particular wall-clock time. So you can have a time zone in New Zealand with a Locale of Japanese, or in this case a time zone in India with presentation formatted for a Québécois person to read.

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ZonedDateTime.now( z );

Generate a String using that localizing formatter object.

String output = zdt.format( f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.