Get Display Name for Day of Week in Different Locale in Java



In this article, we will learn how to get the display name for a day of the week in different locales using Java. The DayOfWeek class in Java provides methods to work with days of the week, and with the help of getDisplayName(), you can retrieve the name of a day in different formats based on the locale.

Java.util.Locale.getDisplayName() Method

The java.util.Locale.getDisplayName(Locale inLocale) method returns a name for the locale that is appropriate for display to the user. This will be the values returned by getDisplayLanguage(), getDisplayCountry(), and getDisplayVariant() assembled into a single string.

Steps to get the display name for a day of the week

The following are the steps to get the display name for a day of the week in different locales ?

  • Step 1. Set the default locale: Create Locale objects for the default locale, Canada, and French.
Locale locale = Locale.getDefault();
Locale locale1 = Locale.CANADA;
  • Step 2. Display the day of the week: Use DayOfWeek.THURSDAY.minus(2) and adjust the day as required.
System.out.printf("%s%n", DayOfWeek.THURSDAY.minus(2).getDisplayName(TextStyle.SHORT, locale));
  • Step 3. Call getDisplayName(): Use getCall getDisplayName() with TextStyle.SHORT and the appropriate locale to get the day's name.
System.out.printf("%s%n", DayOfWeek.SUNDAY.minus(10).getDisplayName(TextStyle.SHORT, locale2));

Java program to get the display name for day of the week in different locales

The following is an example of displaying the name for the day of the week in different locales ?
import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.Locale;
public class Demo {
	public static void main(String[] args) {
		Locale locale = Locale.getDefault();
		Locale locale1 = Locale.CANADA;
		System.out.printf("%s%n", DayOfWeek.THURSDAY.minus(2).getDisplayName(TextStyle.SHORT, locale));
		System.out.printf("%s%n", DayOfWeek.THURSDAY.minus(2).getDisplayName(TextStyle.SHORT, locale1));
		Locale locale2 = Locale.FRENCH;
		System.out.printf("%s%n", DayOfWeek.SUNDAY.minus(10).getDisplayName(TextStyle.SHORT, locale2));
	}
}

Output

Tue
Tue.
jeu.

Code Explanation

The program first sets the Locale objects for the default system locale, Canada, and French locales. By using DayOfWeek.THURSDAY.minus(2), it adjusts the day to Tuesday. The getDisplayName(TextStyle.SHORT, locale) method is then used to get the short name of the day for each locale. The output shows "Tue" for the default and Canada locales, and "jeu." for the French locale.

Updated on: 2024-11-23T03:47:56+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements