gho*_*sio 4 java date datetime-format
我正在尝试格式化LoacalDate,但我没有找到任何信息.我需要格式化为另一种语言.这个案子就是我希望用西班牙语获得一年中的一个月.我正在尝试使用:
Locale locale = new Locale("es", "ES");
Run Code Online (Sandbox Code Playgroud)
但我找不到SimpleDateFormat或类似LocalDate格式.
LocalDate.now().getMonth();
Run Code Online (Sandbox Code Playgroud)
谁能帮我?
对不起,我使用了旧的(也是更常用的)Java日期时间类,因为你谈到的是SimpleDateFormat,它是旧API的一部分.
当您使用java.time.LocalDate
格式化程序时,您必须使用java.time.format.DateTimeFormatter
:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM", aLocale);
final String month = LocalDate.now().format(formatter);
Run Code Online (Sandbox Code Playgroud)
Month
类Wimmer 的答案是正确的。但是,如果您只需要月份名称,请使用Month
该类。这可能会证明更直接,更灵活。
该getDisplayName
方法生成各种长度(缩写)的本地化String。
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
Month month = Month.from( today );
String monthName = month.getDisplayName( TextStyle.FULL_STANDALONE , locale );
Run Code Online (Sandbox Code Playgroud)
请注意,它TextStyle
提供了月份名称的替代“独立”版本。在某些语言中,用作日期时间的一部分时的名称可能与没有特定日期时间的一般名称时的名称不同。