我试图格式化LoacalDate,但我没有找到任何信息。我需要格式化为另一种语言。这个案子就是我希望用西班牙语获得一年中的一个月。我试图使用:
Locale locale = new Locale("es", "ES");
但我找不到SimpleDateFormat或类似LocalDate的格式。
LocalDate.now().getMonth();
任何人都可以帮助我吗?
答案 0 :(得分:8)
很抱歉,我使用了旧的(也是更常用的)Java日期时间类,因为你谈到了SimpleDateFormat,它是旧API的一部分。
当您使用java.time.LocalDate
时,您必须使用的格式化程序是java.time.format.DateTimeFormatter
:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM", aLocale);
final String month = LocalDate.now().format(formatter);
答案 1 :(得分:4)
Month
class The Answer是正确的。但如果您想要的只是月份的名称,请使用Month
类。这可能更直接,更灵活。
getDisplayName
方法生成各种长度(缩写)的本地化字符串。
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
Month month = Month.from( today );
String monthName = month.getDisplayName( TextStyle.FULL_STANDALONE , locale );
请注意,TextStyle
提供了月份名称的替代“独立”版本。在某些语言中,当用作日期时间的一部分时,名称可能会有所不同,而不是在没有特定日期时间的情况下使用。
答案 2 :(得分:1)
我用了这个并且和我一起工作
LocalDate.now().month.getDisplayName(TextStyle.FULL,local)
答案 3 :(得分:-1)
试试这个
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormater {
public static void main(String[] args) {
final Locale spain = new Locale("es", "ES");
Format formatter = new SimpleDateFormat("MMMM",spain);
String s = formatter.format(new Date());
System.out.println(s);
}
}