Search code examples
c++datetimestrftime

C++ strftime() incorrect output


#include <ctime>
#include <iostream>

using namespace std;

int main()
{
    char dateStringBuffer[256] = "";
    tm date;

    date.tm_year = 2017;
    date.tm_mon = 9;
    date.tm_mday = 13;

    strftime(dateStringBuffer, 256, "%d.%m.%Y", &date);
    cout << dateStringBuffer;
}

The output is:

13.10.3917

Expected output:

13.09.2017

It makes no sense to me. What did I do wrong?


Solution

  • The struct tm in corecrt_wtime.h has the following comments next to it's members.

    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    

    which means that you should have done something of this sort :

    date.tm_year = 117;
    date.tm_mon = 8;
    date.tm_mday = 13;
    

    This would give you your expected output of : 13.09.2017