Reputation:
How can I find the DateFormat
for a given Locale
?
Upvotes: 20
Views: 37880
Reputation: 340118
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH );
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 );
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?
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.
Upvotes: 3
Reputation: 134330
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 Date
s:
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();
Upvotes: 25