How do I get day of week?

In this example we want to create a calendar or date from a year and day of the year. Next we will find out what day-of-week that calendar or date represent. In the code snippet below we are trying to find the 180 day of the year 2021.

Let’s see the example below.

package org.kodejava.util;

import java.text.DateFormatSymbols;
import java.util.Calendar;

public class DayOfYearToDayOfWeekExample {
    public static void main(String[] args) {
        // Create a calendar with year and day of year.
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2021);
        calendar.set(Calendar.DAY_OF_YEAR, 180);

        // See the full information of the calendar object.
        System.out.println(calendar.getTime().toString());

        // Get the weekday and print it
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println("Weekday: " + weekday);

        // Get weekday name
        DateFormatSymbols dfs = new DateFormatSymbols();
        System.out.println("Weekday: " + dfs.getWeekdays()[weekday]);
    }
}

Below is the result of our program.

Tue Jun 29 06:04:21 CST 2021
Weekday: 3
Weekday: Tuesday
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.