Get Day of the Week in Java 8

1. Introduction

Retrieving the day of the week is a frequent requirement in applications dealing with calendars, scheduling, or any functionality that depends on the days of the week. Java 8 introduced new APIs in java.time that greatly simplify date-time operations, including obtaining the day of the week.

Key Points

1. LocalDate is used to represent a date without time or timezone information.

2. The getDayOfWeek() method of LocalDate returns a DayOfWeek enum, which represents the seven days of the week.

3. This method is useful for conditional logic based on day-specific operations.

2. Program Steps

1. Import the java.time.LocalDate and java.time.DayOfWeek classes.

2. Get the current date.

3. Retrieve the day of the week from the date.

3. Code Program

import java.time.LocalDate;
import java.time.DayOfWeek;

public class DayOfWeekFinder {

    public static void main(String[] args) {
        // Step 2: Get the current date
        LocalDate today = LocalDate.now();

        // Step 3: Retrieve the day of the week
        DayOfWeek dayOfWeek = today.getDayOfWeek();

        // Print the day of the week
        System.out.println("Today is: " + dayOfWeek);
    }
}

Output:

Today is: TUESDAY  // Output will vary based on the current day

Explanation:

1. LocalDate.now() fetches the current date according to the system clock and the default time-zone.

2. today.getDayOfWeek() retrieves the day of the week as a DayOfWeek enum value, which includes descriptive values like MONDAY, TUESDAY, etc.

3. This output is particularly valuable for tasks that require specific actions on certain days, such as triggering weekly reports or sending notifications.


Comments