tl;博士
String output =
ZonedDateTime.now ( ZoneId.of ( "Europe/Madrid" ) )
.format (
DateTimeFormatter.ofLocalizedDate ( FormatStyle.FULL )
.withLocale ( new Locale ( "es" , "ES" ) )
)
;
martes 12 de julio de 2016
详
阿菲接受的答案是正确的。您错误地构造了一个对象。Locale
java.time
“问题”和“答案”都使用旧的过时类,现在被 Java 8 及更高版本中内置的 java.time 框架所取代。这些类取代了旧的麻烦的日期时间类,例如 .请参阅 Oracle 教程。许多java.time功能在ThreeTen-Backport中向后移植到Java 6和7,并在ThreeTenABP中进一步适应Android。java.util.Date
这些类包括 DateTimeFormatter
,用于在从日期时间值生成 String 时控制文本的格式。您可以指定显式格式设置模式。但为什么要打扰呢?让班级自动将格式本地化为人类语言和文化规范的特定。Locale
例如,获取马德里地区时区的当前时刻。
ZoneId zoneId = ZoneId.of( "Europe/Madrid" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
// example: 2016-07-12T01:43:09.231+02:00[Europe/Madrid]
实例化格式化程序以生成一个 String 来表示该日期-时间值。通过 FormatStyle
指定文本的长度(完整、长、中、短)。
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.FULL );
应用语言环境
以替换分配给格式化程序的 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