Day of the Week | Algorithm & Data Structure

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a date, write a program to return the corresponding day of the week for that date.

The input date is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}.

Example 

Day of the Week

Input :- Day = 31, Month = 8, Year = 2019
Output :- "Saturday"
Input :- Day = 15, Month = 8, Year = 1993
Output :- "Sunday"

Solution

Calculate the total number of days from 1st January 1971 to input day, then take its modulus by 7 and return the day of the week.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String result = main.dayOfTheWeek(15, 8, 1993);
		System.out.println(result);
	}
	
	/* Solution */    
	public String dayOfTheWeek(int day, int month, int year) {
        
        int totalDays = 0;
        
        for(int i=1971; i<year; i++){            
            totalDays = totalDays + getDaysOfYear(i);            
        }
        
        for(int i=1; i<month; i++){ 
            totalDays = totalDays + getDaysOfMonth(i); 
        } 

        if(month > 2 && getDaysOfYear(year) == 366){
            totalDays++;
        }
        
        totalDays = totalDays + day;
        return getDayOfWeek(totalDays%7);        
    }
    
    public String getDayOfWeek(int day){        
        switch(day){            
            case 1 : return "Friday";
            case 2 : return "Saturday";
            case 3 : return "Sunday";
            case 4 : return "Monday";
            case 5 : return "Tuesday";
            case 6 : return "Wednesday";
            case 0 : return "Thursday";
        }
        return "Sunday";
    }
    
    public int getDaysOfYear(int year){        
        if(year % 100 == 0){
            if(year % 400 == 0){
                return 366;
            }else {
                return 365;
            }
        }
        if(year % 4 == 0){
            return 366; 
        }else {
            return 365;
        }
    }
    
    public int getDaysOfMonth(int month){        
        switch(month){                
            case 1: return 31;
            case 2: return 28;
            case 3: return 31;
            case 4: return 30;
            case 5: return 31;
            case 6: return 30;
            case 7: return 31;
            case 8: return 31;
            case 9: return 30;
            case 10: return 31;
            case 11: return 30;
            case 12: return 31;
        }
        return 30;
    }
}

Result

Sunday

Similar Post

  1. Move Zeroes to End of Array
  2. Find Pivot Index in Array
  3. Rotate Array

That’s all for Day of the Week in Java, If you liked it, please share your thoughts in a comments section and share it with others too.