Q:

C++ program to get week day from given date

0

C++ program to get week day from given date

Given a date, and we have to find weekday like Sunday, Monday etc from given date.

Here, we are using given formula to get the weekday number from 0 to 6 and behalf on this weekday number, we are able to get the weekday from declared array (we have to declare an array of strings with weekday names).

	int rst =                                                     
		dd                                                      
		+ ((153 * (mm + 12 * ((14 - mm) / 12) - 3) + 2) / 5) 
		+ (365 * (yy + 4800 - ((14 - mm) / 12)))
		+ ((yy + 4800 - ((14 - mm) / 12)) / 4)
		- ((yy + 4800 - ((14 - mm) / 12)) / 100)
		+ ((yy + 4800 - ((14 - mm) / 12)) / 400)
		- 32045;

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#include<iostream>
using namespace std;

//function to get date and return weekday number [0-6]
int getWeekDay(int yy, int mm, int dd) 
{
	//formula to get weekday number
	int rst =                                                     
		dd                                                      
		+ ((153 * (mm + 12 * ((14 - mm) / 12) - 3) + 2) / 5) 
		+ (365 * (yy + 4800 - ((14 - mm) / 12)))
		+ ((yy + 4800 - ((14 - mm) / 12)) / 4)
		- ((yy + 4800 - ((14 - mm) / 12)) / 100)
		+ ((yy + 4800 - ((14 - mm) / 12)) / 400)
		- 32045;

	return (rst+1)%7 ;
}

//main program/code
int main()
{
	//declaring array of weekdays`
	const char *Names[] = {"Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};
	int day = 0;
	//calling function, storing weekday number in day
	day= getWeekDay(2017,6,24);
	//printing the weekday from given array
	cout<<"Day : "<<Names[day]<<endl;

	return 0;    
}

Output

Day : Saturday

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
Find last index of a character in a string using C... >>
<< Set date and time in Linux Operating System using ...