This quick code tip shows how to get localized day of the week and month for a date(
LocalDateTime) in French or Spanish using
java.util.Locale in Java 8 with examples.
- First a
localDate, is created using
localDatehas the value ‘
- To convert the date into French, i.e. with French names for weekdays and months,
LocalDate.format()method is used with 2 parameters.
- The 1st parameter is a
java.time.format.DateTimeFormatterinstance with format –
"EEEE, dd MMMM, yyyy".
EEEEspecifies the full name of weekday.
MMMMspecifies the full name of the month.
ddis 2-digit date and
yyyyis 4-digit year.
- The 2nd parameter specifies the locale using a
java.util.Localeinstance. Since, the date is to be formatted in French, so
dateInFrenchis printed and is correctly output as ‘
vendredi, 01 janvier, 2016’.
localDatein Spanish requires code similar to French formatting with only one difference. Since, there is no pre-defined constant for Spanish locales, hence an instance of
Localefor Spanish is created using the constructor –
new Locale("es", "ES"), where
esis value for language(spanish) and
ESis the value for country(Spain).
dateInSpanishis printed and is correctly output as ‘
viernes, 01 enero, 2016’.
- The code for formatting
LocalDateTimein French or Spanish will be the same as we used for LocalDate; including the methods used and values passed.
- Similar to Spanish and French dates, dates in any language such as Italian, German etc, will also be coded in the same way with just the
Localeinstance changed to that specific country/language.
- Lastly, I have formatted
localDateusing my system’s (and JVM’s) default locale(English) obtained using