Home » C++ programs » C++ Most popular & searched programs

C++ program to get week day from given date

Learn: How to get weekday from a given date in C++ program? Here I am writing a C++ code by using you can able to access the weekday of 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;

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.