2

I can't understand why the tm struct in C++ behaves this way. Let me be more specific - if I were to get the current time, I'd probably do something like this

time_t now = time(0);
tm *nowTm = gmtime(&now);

And upon printing out the date, I expect something like 2015/06/13 (the current date as of this post)

cout << nowTm->tm_year << "/" << nowTm->tm_mon << "/" << nowTm->tm_mday;

But instead, I find out that it prints out 1150/5/13 instead. For the month value, I simply added 1 to set it to the correct month, but playing around with the year proved troublesome.

I came across this SO post: Algorithm to add or subtract days from a date?, which said to subtract 1900 from the year to get the correct year. I tried that to no avail.

I then tried adding on the difference between the current year and 1150, 2015 - 1150 = 865 to get the correct year, but it gave me 9800 instead of 2015.

I then experimented with adding for the year, and found that

  1. If I +1 to the year, it goes up in increments of 10 years.
  2. If I +0.1 to the year, it would divide the date by zero and add 0.1 to it (e.g. 1150 + 1 = 115.01).

I'm confused - why does this happen and how do I get the correct year in my tm struct?

Community
  • 1
  • 1
Code Apprentice
  • 522
  • 2
  • 7
  • 19

1 Answers1

6

From the documentation on tm we can see that:

  • tm_year is years since 1900, not the current year number, i.e. it should be 115 this year.
  • tm_mon is months since January (range 0-11), not the number of the month.

So what you need is:

std::cout << 1900 + nowTm->tm_year
   << "/" << 1 + nowTm->tm_mon
   << "/" << nowTm->tm_mday;
Emil Laine
  • 41,598
  • 9
  • 101
  • 157