无法使用 Locale("es_ES") 将日期翻译为西班牙语

问题描述 投票:0回答:5

我正在尝试做一个简单的日期格式,它确实工作得很好,非常简单,但问题是语言。我使用区域设置“es_ES”来获取“Miércoles”而不是“Wednesday”,类似这样,但我失败了。

这是我的代码:

SimpleDateFormat formato = 
    new SimpleDateFormat("EEEE d 'de' MMMM 'de' yyyy", new Locale("es_ES"));
String fecha = formato.format(new Date());

fecha
字符串的预期值为:

2012 年 4 月 Miércoles 4

但我仍然得到:

2012 年 4 月 4 日星期三

我做错了什么?

java date locale
5个回答
97
投票

“es_ES”是语言+国家。 您必须单独指定每个部分。

Locale
的构造函数是:

您想要

new Locale("es", "ES");
获取与 es_ES 一起使用的区域设置。

但是,最好使用

Locale.forLanguageTag("es-ES")
,使用格式良好的 IETF BCP 47 语言标签
es-ES
(使用
-
而不是
_
),因为该方法可以返回缓存的
Locale
,而不是总是创建一个新的。


7
投票

tl;博士

String output = 
    ZonedDateTime.now ( ZoneId.of ( "Europe/Madrid" ) )
    .format ( 
        DateTimeFormatter.ofLocalizedDate ( FormatStyle.FULL )
                         .withLocale ( new Locale ( "es" , "ES" ) ) 
    )
;

2016 年 7 月 12 日营销

详情

Affe

接受的答案是正确的。您错误地构建了 Locale

 对象。

java.time

问题和答案都使用旧的过时类,现在已被 Java 8 及更高版本中内置的

java.time 框架取代。这些类取代了旧的麻烦的日期时间类,例如 java.util.Date

。请参阅
Oracle 教程。许多 java.time 功能在 ThreeTen-Backport 中向后移植到 Java 6 和 7,并在 ThreeTenABP 中进一步适应 Android。

这些类包括

DateTimeFormatter

,用于在从日期时间值生成字符串时控制文本格式。您可以指定显式格式模式。但何苦呢?让班级自动将格式本地化为特定Locale
的人类语言和文化规范。

例如,获取

马德里地区时区的当前时刻。

ZoneId zoneId = ZoneId.of( "Europe/Madrid" ); ZonedDateTime zdt = ZonedDateTime.now( zoneId ); // example: 2016-07-12T01:43:09.231+02:00[Europe/Madrid]

实例化格式化程序以生成表示该日期时间值的字符串。通过

FormatStyle

 指定文本长度(全、长、中、短)。

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.FULL );

应用

Locale

替代分配给格式化程序的JVM的当前默认值Locale

Locale locale = new Locale ( "es" , "ES" ); formatter = formatter.withLocale ( locale );

使用格式化程序生成 String 对象。

String output = zdt.format ( formatter ); // example: martes 12 de julio de 2016

转储到控制台。

System.out.println ( "zdt: " + zdt + " with locale: " + locale + " | output: " + output );

zdt:2016-07-12T01:43:09.231+02:00[欧洲/马德里],区域设置:es_ES |输出:martes 12 de julio de 2016


4
投票
Java 8+

java.time.DayOfWeek

 自动本地化。

LocalDate today = LocalDate.now(); DayOfWeek dow = today.getDayOfWeek() ; String day = dow.getDisplayName(TextStyle.FULL, new Locale("es","ES"))); // Or `Locale.of( "es" , "ES" )` in modern Java.
也适用于 

java.time.Month


    


3
投票
Locale spanishLocale=new Locale("es", "ES"); String dateInSpanish=localDate.format(DateTimeFormatter.ofPattern("EEEE, dd MMMM, yyyy",spanishLocale)); System.out.println("'2016-01-01' in Spanish: "+dateInSpanish);
    

2
投票
Locale esLocale = new Locale("es", "ES");//para trabajar en español SimpleDateFormat formatter = new SimpleDateFormat(strFormatoEntrada, esLocale);//El formato con que llega mi strFecha más el lenguaje
    
© www.soinside.com 2019 - 2024. All rights reserved.