ghossio
ghossio

Reputation: 152

Localdate: format with locale

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?

Upvotes: 12

Views: 25429

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 340118

tl;dr

Month
.from(
    LocalDate.now()
)
.getDisplayName( 
    TextStyle.FULL_STANDALONE , 
    new Locale( "es" , "ES" )
)

See this code run live at IdeOne.com.

julio

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.

Upvotes: 14

Mahmoud Mabrok
Mahmoud Mabrok

Reputation: 1482

I used this and worked with me

LocalDate.now().month.getDisplayName(TextStyle.FULL,local)

Upvotes: 1

Matthias Wimmer
Matthias Wimmer

Reputation: 4009

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

Upvotes: 18

Related Questions