×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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.
[Last updated : February 26, 2023]

Problem statement

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

Getting week day from given date in C++

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;

C++ code to get the week day from given date

#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

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.