Get Day of Week from Specific Date in Java: Easy Tutorial

If you're working on a Java project that requires you to get the day of the week from a specific date, you're in luck. Java provides a simple way to do this using the Calendar class.

First, create a Calendar object and set it to the desired date using the set method. For example, to get the day of the week for January 1, 2022:


Calendar cal = Calendar.getInstance();
cal.set(2022, Calendar.JANUARY, 1); 

Next, use the get method with the Calendar.DAY_OF_WEEK constant to retrieve the day of the week as an integer, where Sunday is 1 and Saturday is 7.


int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

To convert this integer to a more readable format, you can use a switch statement or an array to map the integer to the corresponding day of the week name.

Here's an example using a switch statement:


String dayOfWeekName;
switch (dayOfWeek) {
    case Calendar.SUNDAY:
        dayOfWeekName = "Sunday";
        break;
    case Calendar.MONDAY:
        dayOfWeekName = "Monday";
        break;
    case Calendar.TUESDAY:
        dayOfWeekName = "Tuesday";
        break;
    case Calendar.WEDNESDAY:
        dayOfWeekName = "Wednesday";
        break;
    case Calendar.THURSDAY:
        dayOfWeekName = "Thursday";
        break;
    case Calendar.FRIDAY:
        dayOfWeekName = "Friday";
        break;
    case Calendar.SATURDAY:
        dayOfWeekName = "Saturday";
        break;
    default:
        dayOfWeekName = "Invalid day of week";
        break;
}

Now you have the day of the week as a string in the dayOfWeekName variable.

In conclusion, getting the day of the week from a specific date in Java is easy using the Calendar class. Simply create a Calendar object, set it to the desired date, and retrieve the day of the week using the get method with the Calendar.DAY_OF_WEEK constant. With a little extra code, you can convert the integer value to a more readable string format.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information