Print day of week using Gregorian Calendar in java

Given a date, you have to print the day of the week.

Examples:

Input : 2018 3 26
Output : Mon

Input : 2010 8 9
Output : Wed

The idea is to use java built-in API Gregorian Calendar.
GregorianCalendar is a concrete subclass of Calendar and provides
the standard calendar system used by most of the world.
GregorianCalendar(int year, int month, int dayOfMonth) constructs a
GregorianCalendar with the given date set in the default time zone
with the default locale.
Several conditions are created to check the validity of
the input data. If an input is found to be wrong an Invalid
message will be printed as output.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Necessary imports for using Gregorian Calendar
import java.util.Calendar;
import java.util.GregorianCalendar;
  
class GFG {
    static int method(int year, int month, int day)
    {
        // to check the validity of day of month
        int[] darr = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  
        // check validity of year and month
        if (year > 0 && (month > 0 && month <= 12)) {
  
            // check for a leap year and month of February
  
            if ((year % 4 == 0 || year % 400 == 0) && 
                month == 2 && (day > 0 && day <= 29)) {
  
                // month starts at zero, so we need to put ( month - 1 ).
                Calendar calendar = new GregorianCalendar(year, month - 1, day);
                return calendar.get(Calendar.DAY_OF_WEEK);
            }
            else {
  
                // check the range of day of month
                if (day > 0 && day <= darr[month - 1]) {
  
                    // month starts at zero, so we need to put ( month - 1 ).
                    Calendar calendar = new GregorianCalendar(year, month - 1, day);
                    return calendar.get(Calendar.DAY_OF_WEEK);
                }
                else
                    return 0;
            }
        }
        else
            return 0;
    }
    public static void main(String[] args)
    {
        String[] dayofweek = { "Invalid", "Sun", "Mon", "Tue",
                                "Wed", "Thur", "Fri", "Sat" };
        int y = 2018, m = 3, d = 26;
        System.out.println(dayofweek[method(y, m, d)]);
    }
}

chevron_right


Output:

Mon


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.