Search code examples
c++ctimedayofweek

How to find the day of the week `tm_wday` from a given date?


To find the day (number) for a given date, I wrote below code using <ctime>:

tm time {ANY_SECOND, ANY_MINUTE, ANY_HOUR, 21, 7, 2015 - 1900};
mktime(&time); //                          today's date                     
PRINT(time.tm_wday);  // prints 5 instead of 2 for Tuesday

According to the documentation, tm_wday can hold value among [0-6], where 0 is Sunday. Hence for Tuesday (today), it should print 2; but it prints 5.
Actually tm_wday gives consistent results, but with a difference of 3 days.
What is wrong here?


Solution

  • You got the month wrong, tm_mon is the offset since January, so July is 6. From the manpage:

    tm_mon The number of months since January, in the range 0 to 11.

    This outputs 2:

    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    
    int main(void) {
        struct tm time;
        memset(&time, 0, sizeof(time));
    
        time.tm_mday = 21;
        time.tm_mon = 6;
        time.tm_year = 2015-1900;
    
        mktime(&time);
    
        printf("%d\n", time.tm_wday);
    
        return 0;
    }
    

    Note that you should initialize the other fields to 0 with memset(3) or similar.