Determine the day of the week for the given date C program example

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: How to use time and date related C functions to determine the day of the week for the given date in C program example

To show: How to use the C date and time functions to determine the day of the week for the given date

 

 

// Converting time to calendar format and then determine the day

#include <stdio.h>

#include <time.h>

 

// a pointer to an array of strings

char *wday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Unknown"};

 

int main(void)

{

// structure data type

struct tm time_check;

// normal data type

int year, month, day;

 

// Input a year, month and day to find the weekday for...

printf("WHAT DAY?...Enter any year, month and day\n");

printf("Year format-YYYY, Month format-MM, Day format-DD\n");

printf("Year: ");

/* scanf("%d", &year); */

scanf_s("%d", &year, 1);

printf("Month: ");

scanf_s("%d", &month, 1);

printf("Date: ");

scanf_s("%d", &day, 1);

 

// load the time_check structure with the data

time_check.tm_year = year - 1900;

time_check.tm_mon = month - 1;

time_check.tm_mday = day;

time_check.tm_hour = 0;

time_check.tm_min = 0;

time_check.tm_sec = 1;

time_check.tm_isdst = -1;

 

// call mktime() function to fill in the weekday field of the structure...

if(mktime(&time_check) == -1)

time_check.tm_wday = 7;

 

// print out the day of the week...

printf("That day is a %s\n", wday[time_check.tm_wday]);

return 0;

}

 

Output example:

 

WHAT DAY?...Enter any year, month and day

Year format-YYYY, Month format-MM, Day format-DD

Year: 1971

Month: 05

Date: 07

That day is a Friday

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index