java

How to get a day of the week by passing specific date and time in Java

Especially in English-speaking countries, the use of the calendar week is very common. The calculation and conversion are done with the class LocalDate in Java 8 and with Calendar in Java before version 8.

To get the specified day of a week. It can be achieved in two ways using Calendar class or using SimpleDateFormat class :
 

How To Get Day Of A Week Using Calendar Class

We can use the Calendar class to get a day of a week by passing a specific date in java as shown in the following example:

// Get date of a week 
public static String getWeek(Date date){
    String[] weeks = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
    if(week_index < 0){
        week_index = 0;
    }
    return weeks[week_index];
}
 

How To Get Day Of A Week Using SimpleDateFormat Class

We can use the SimpleDateFormat class to get a day of a week by passing a specific date in java as shown in the following example:

// Get day of a week according to date 
public static String getWeek(Date date){
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    String week = sdf.format(date);
    return week;
}
Note: The string format is case sensitive.

For the parameters passed in to create SimpleDateFormat: EEEE stands for week, Such as “Thursday”; MMMM represents month, such as “November”; MM represents month, such as “11”;

yyyy represents the year, such as “2010”; dd represents the day, such as “25”.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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