I'm trying to do a simple date format, it does work great, it's very easy, but the problem is the language. I used the locale "es_ES" to get "Miércoles" instead of "Wednesday" and sorts like that but i failed.
Here's my code:
SimpleDateFormat formato =
new SimpleDateFormat("EEEE d 'de' MMMM 'de' yyyy", new Locale("es_ES"));
String fecha = formato.format(new Date());
The EXPECTED value of the fecha
string is:
Miércoles 4 de Abril de 2012
but i'm still getting:
Wednesday 4 de April de 2012
What am I doing wrong?
"es_ES" is a language + country. You must specify each part separately.
The constructors for
Locale
are:Construct a locale from a language code.
Construct a locale from language, country.
Construct a locale from language, country, variant.
You want
new Locale("es", "ES");
to get the Locale that goes with es_ES.However, it would be better to use
Locale.forLanguageTag("es-ES")
, using the well-formed IETF BCP 47 language tages-ES
(with-
instead of_
), since that method can return a cachedLocale
, instead of always creating a new one.Java 8
Also works for month.
tl;dr
Details
The accepted Answer by Affe is correct. You were incorrectly constructing a
Locale
object.java.time
The Question and Answer both use old outmoded classes now supplanted by the java.time framework built into Java 8 and later. These classes supplant the old troublesome date-time classes such as
java.util.Date
. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.These classes include the
DateTimeFormatter
to control the format of text when generating a String from your date-time value. You can specify an explicit formatting pattern. But why bother? Let the class automatically localize the format to the human language and cultural norms of a specificLocale
.For example, get the current moment in Madrid regional time zone.
Instantiate a formatter to generate a String to represent that date-time value. Specify the length of the text via
FormatStyle
(full, long, medium, short).Apply a
Locale
to substitute for the JVM’s current defaultLocale
assigned to the formatter.Use the formatter to generate a String object.
Dump to console.