MENU

Java Finds the current (today's) day of the week

TOC

java Get the current (today's) day of the weekThe following is a list of the most common problems with the Calendar.DAY_OF_WEEK

Java The following is a sample program to obtain the current (today's) day of the week using the Calendar class in

To acquire, Calendar.DAY_OF_WEEK to be used.

Calendar cal = Calendar.getInstance();
int week = cal.get(Calendar.DAY_OF_WEEK);

Calendar.DAY_OF_WEEKThe return value that can be obtained with the "return" statement is a number from 1 to 7, with Sunday starting with 1, so the sample program uses a switch statement to determine the day of the week.

sample program

/**
 * @return current day of the week.
 * @return current day of the week
 */
public static String getDayOfTheWeek() {
    Calendar cal = Calendar.getInstance();
    switch (cal.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.SUNDAY: return "Sunday";
        
        TUESDAY: return "Tuesday"; case Calendar.
        WEDNESDAY: return "Wednesday"; case Calendar.
        THURSDAY: return "Thursday"; case Calendar.
        FRIDAY: return "Friday"; case Calendar.
        SATURDAY: return "Saturday"; case Calendar.
    }
    throw new IllegalStateException(); }
}
/**
 * Returns the current day of the week.
 * * Omit the day of the week.
 * @return current day of the week
 */
public static String getDayOfTheWeekShort() {
    Calendar cal = Calendar.getInstance();
    switch (cal.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.SUNDAY: return "day";
        case Calendar.MONDAY: return "month"; case Calendar.TUESDAY: return "month";
        TUESDAY: return "fire"; case Calendar.
        WEDNESDAY: return "water"; case Calendar.
        THURSDAY: return "Thursday"; case Calendar.
        FRIDAY: return "Friday"; case Calendar.
        SATURDAY: return "SATURDAY"; case Calendar.SATURDAY: return "SATURDAY"; }
    }
    throw new IllegalStateException(); }
}	


Execution Result

◆Example of Execution

public static void main(String[] args) {
    // Display today's day of the week.
    System.out.println("Today is " + getDayOfTheWeek() + ")") ;
    // Display today's day of the week. Abbreviation.
    System.out.println("Today is " + getDayOfTheWeekShort() + ")) ;
}

◆Output result

Today is "Wednesday.
Today is "Wednesday.
TOC