Localdate: format with locale

喜欢而已 提交于 2020-01-23 06:53:08

问题


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:

Locale locale = new Locale("es", "ES");

But I don't find a SimpleDateFormat or similar to the format LocalDate.

LocalDate.now().getMonth();

Can anyone help me?


回答1:


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.

When you are using java.time.LocalDate the formatter you have to use is java.time.format.DateTimeFormatter:

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM", aLocale);
final String month = LocalDate.now().format(formatter);



回答2:


Month class

The Answer by 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.

The getDisplayName method generates a localized String in various lengths (abbreviations).

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.




回答3:


Try this

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);
   }
}


来源:https://stackoverflow.com/questions/35581921/localdate-format-with-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!