java 本地日期:带有语言环境的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35581921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Localdate: format with locale
提问by ghossio
I'm attempting to format a LoacalDate but I didn't find any information. I need to format to another language. The case is simply I want to get the month of the year in Spanish. I'm trying to use:
我正在尝试格式化 LoacalDate 但我没有找到任何信息。我需要格式化为另一种语言。案例只是我想用西班牙语获得一年中的月份。我正在尝试使用:
Locale locale = new Locale("es", "ES");
But I don't find a SimpleDateFormat or similar to the format LocalDate.
但我没有找到 SimpleDateFormat 或类似于 LocalDate 的格式。
LocalDate.now().getMonth();
Can anyone help me?
谁能帮我?
回答by Matthias Wimmer
Sorry, I used the older (and still more commonly used) date time classes of Java, as you spoke about SimpleDateFormat which is part of the older API.
抱歉,当您谈到 SimpleDateFormat 时,我使用了 Java 的较旧(并且仍然更常用)的日期时间类,它是旧 API 的一部分。
When you are using java.time.LocalDate
the formatter you have to use is java.time.format.DateTimeFormatter
:
当您使用java.time.LocalDate
格式化程序时,您必须使用的是java.time.format.DateTimeFormatter
:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM", aLocale);
final String month = LocalDate.now().format(formatter);
回答by Basil Bourque
Month
class
Month
班级
The Answerby Wimmer is correct. But if all you want is the name of the month, use the Month
class. That may prove more direct and more flexible.
Wimmer的答案是正确的。但是,如果您只想要月份的名称,请使用Month
该类。这可能更直接、更灵活。
The getDisplayName
method generates a localized String in various lengths (abbreviations).
该getDisplayName
方法生成各种长度(缩写)的本地化字符串。
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
Month month = Month.from( today );
String monthName = month.getDisplayName( TextStyle.FULL_STANDALONE , locale );
“standalone” Month Name
“独立”月份名称
Note that TextStyle
offers alternative “standalone” versions of a month name. In some languages the name may be different when used as part of a date-time versus when used in general without a specific date-time.
请注意,它TextStyle
提供了月份名称的替代“独立”版本。在某些语言中,名称在用作日期时间的一部分时与在没有特定日期时间的情况下一般使用时可能会有所不同。