iammilind
iammilind

Reputation: 69988

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?

Upvotes: 2

Views: 10179

Answers (2)

NathanOliver
NathanOliver

Reputation: 180510

The reason you are getting invalid output is that you are using the wrong month. tm_mon starts at 0 and not 1. you can see tghis by using this code:

tm time {50, 50, 12, 21, 7, 2015 - 1900};
time_t epoch = mktime(&time);
printf("%s", asctime(gmtime(&epoch)));

Output:

Fri Aug 21 12:50:50 2015

Live Example

Upvotes: 0

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

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.

Upvotes: 6

Related Questions