2

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?

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Choose a language. C or C++ and stick to it. Do not change your code after getting an answer. It usually makes the answer invalid. – Sourav Ghosh Jul 21 '15 at 12:24
  • @SouravGhosh, I don't see a need for sticking to only 1 of them. `` and `` are available in C and C++ respectively. Having both the tags on gives better visibility. The code is unchanged, just `std::` is removed from the code, to avoid someone untagging from C. That makes no difference. – iammilind Jul 21 '15 at 12:27
  • 1
    your code is in `C`. Why tag `c++` then? – Sourav Ghosh Jul 21 '15 at 12:33

2 Answers2

6

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.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
  • My bad. I never cared on checking the month :-). With brace initializer, I believe the rest of the fields will be initialized to 0 automatically. Hence `memset()` is not required. – iammilind Jul 21 '15 at 12:42
0

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

NathanOliver
  • 171,901
  • 28
  • 288
  • 402