KOB
KOB

Reputation: 1216

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?

Upvotes: 0

Views: 1173

Answers (3)

Vishaal Shankar
Vishaal Shankar

Reputation: 1658

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

Upvotes: 3

Robert Kock
Robert Kock

Reputation: 6038

The tm_year is the number of years after 1900.
The tm_mon is the month within the year where January corresponds with 0.

Upvotes: 1

Alan Birtles
Alan Birtles

Reputation: 36614

std::tm's members don't all take raw date values, see http://en.cppreference.com/w/cpp/chrono/c/tm

tm_myear is the years since 1900 and tm_mon uses 0 for January

Upvotes: 1

Related Questions