Java Program to Display Name of the Weekdays in Calendar Year


A week in a calendar year consists of 5 weekdays: Monday, Tuesday, Wednesday, Thursday and Friday; the two remaining days (Saturday and Sunday) make up the weekend. If you're working with dates and calendars as an application developer, manually looking up names for weekdays in a year can be tedious. In this article we will take a deeper dive into various approaches using built-in classes and APIs with detailed code examples provided for both beginners and experienced Java developers alike - giving valuable techniques for simplifying a calendar-related task i.e. to Display Name of the Weekdays in Calendar Year using Java programming languages. The following are the different types of methods to display names of weekdays −

  • Naïve Method

  • Using the java.text.DateFormatSymbols class

  • Using the java.util.Calendar class

  • Using the java.time.format.DateTimeFormatter class

  • Using the java.util.Date and java.text.SimpleDateFormat classes

Approach 1: Naïve Method

This is the simplest approach and requires hardcoding the names of each weekday into an array. We then use for each loop to iterate over this array and display their names.

Example

public class Weekdays {
   public static void main(String[] args) {
      String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
      for (String day : weekdays) {
         System.out.println(day);
      }
   }
}

Output

Monday
Tuesday
Wednesday
Thursday
Friday

Approach 2: Using the java.text.DateFormatSymbols Class

The Java standard library's java.text package contains the java.text class, which provides a set of symbols used by SimpleDateFormat to format and parse dates and times according to an established pattern. The DateFormatSymbols class provides methods for retrieving and setting the following date and time symbols −

  • Month and day names and abbreviations

  • Day of the week names and abbreviations

  • Era names

  • AM/PM strings

  • Time Zone Names and Abbreviations

DateFormatSymbols by default uses the locale-specific symbols for the current default Locale. However, you can create an instance of DateFormatSymbols with a different Locale or custom symbol arrays for any of the above fields. We will make use of the getWeekdays() function which returns an array of weekday names.

Example

import java.text.DateFormatSymbols;

public class Weekdays {
   public static void main(String[] args) {
      DateFormatSymbols symbols = new DateFormatSymbols();
      String[] weekdays = symbols.getWeekdays();
      for (int i = 2; i <= 6; i++) {
         System.out.println(weekdays[i]);
      }
   }
}

Output

Monday
Tuesday
Wednesday
Thursday
Friday

Approach 3: Using the java.util.Calendar Class

The Java standard library's java.util package contains the java.util class, which provides an intuitive, locale-independent way of working with dates and times.

Calendar is an intuitive system that enables date and time manipulation in various ways. It offers methods for retrieving or setting various fields of a date or time, such as year, month, day, hour, minute, second and millisecond; additionally it permits operations on these values like adding or subtracting seconds.

Calendar is an abstract class, so you cannot create an instance directly. Instead, use the getInstance() static factory method to create an instance based on your current time zone and locale settings. Alternatively, use the getInstance(TimeZone zone, Locale aLocale) method for creating a Calendar instance with specific preferences in regard to these factors.

Calendar offers several useful features, like Time zone support, Leap year support as well as Field normalization.

Example

import java.util.Calendar;
import java.util.Locale;

public class Weekdays {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      for (int i = Calendar.MONDAY; i <= Calendar.FRIDAY; i++) {
         calendar.set(Calendar.DAY_OF_WEEK, i);
         String name = calendar.getDisplayName(
            Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
            System.out.println(name);
      }
   }
}

Output

Monday
Tuesday
Wednesday
Thursday
Friday

Approach 4. Using the java.time.format.DateTimeFormatter Class

The Java 8 Date-Time API, particularly the java.time package, includes a DateTimeFormatter class which offers flexible and thread-safe date/time formatting capabilities.

DateTimeFormatter is an application used for formatting and parsing date and time objects. It offers various options for creating formatters based on various patterns such as date-only, time-only or both. Furthermore, it supports multiple chronologies including both ISO calendar systems and non-ISO calendar systems.

DateTimeFormatter can parse and format localized text, such as month and day names, into pattern letters that represent different fields within a date or time object. It supports certain fields like year, month, day, hour, minute, second (including fractions thereof) in these same pattern letters.

DateTimeFormatter is both thread-safe and immutable, allowing you to reuse the same formatter instance across multiple threads.

Example

import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;

public class Weekdays {
   public static void main(String[] args) {
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE", Locale.getDefault());
      int c=0;
      for (DayOfWeek day : DayOfWeek.values()) {
         if(c<5)
         {
            String name = day.getDisplayName(TextStyle.FULL, Locale.getDefault());
            System.out.println(name);
            c++;
         }
      }
   }
}

Output

Monday
Tuesday
Wednesday
Thursday
Friday

Approach 5: Using the java.util.Date and java.text.SimpleDateFormat Classes

Java's standard library provides two classes for working with dates and times: java.util.Date and java.text.SimpleDateFormat.

Java.util.Date provides the capability of representing an exact moment in time with millisecond precision, measured relative to the "epoch" - January 1, 1970 at 00:00:00 GMT. Date provides methods for manipulating date and time values such as getting or setting year, month, day, hour, minute, second values; however it has since been replaced by the java.time package introduced in Java 8 instead.

Java.text.SimpleDateFormat is a class that formats and parses dates and times according to an established pattern. It takes an input string specifying how dates should be formatted or parsed; this format string consists of various pattern letters representing fields within a date or time value such as year, month, day, hour, minute, second, and fraction of second.

SimpleDateFormat is not thread-safe, and its use in a multi-threaded environment is discouraged. Instead, the java.time.format.DateTimeFormatter class should be utilized for formatting and parsing dates and times.

Example

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Weekdays {
   public static void main(String[] args) {
      SimpleDateFormat simpleDF = new SimpleDateFormat("EEEE", Locale.getDefault());
      for (int i = 6; i <= 10; i++) {
         Date date = new Date();
         date.setDate(i);
         String name = simpleDF.format(date);
         System.out.println(name);
      }
   }
}

Output

Thursday
Friday
Saturday
Sunday
Monday

Conclusion

Java offers a wide range of libraries which make displaying weekdays from Monday to Friday of a calendar year easy. A total of six techniques have been demonstrated above, all requiring only minimal modifications if one needs to display even weekend days within that same calendar year.

Updated on: 06-Apr-2023

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements