tags:

views:

75

answers:

3

Hi guys, i have the following code below:

const char* timeformat = "%Y-%m-%d %H:%M:%S";
const int timelength = 20;
char timecstring[timelength];

strftime(timecstring, timelength, timeformat, currentstruct);

cout << "timecstring is: " << timecstring << "\n";

currentstruct is a tm*. The cout is giving me the date in the correct format, but the year is not 2010, but 3910. I know there is something to do with the year cound starting at 1900, but im not sure how to get strftime to recognise this and not add 1900 to the value of 2010 that is there, can anyone help.

Regards

Paul

+5  A: 

The tm_year field of a struct tm is, by definition, the number of years since 1900. Every piece of code that deals with a struct tm expects this to be the case. You can't set tm_year to 2010 and expect code to magically determine that you really mean the year 2010 and not the year 3910.

Set tm_year to 110, and strftime will work.

Josh Kelley
+3  A: 

When you put the year into your currentstruct, you're apparently putting in 2010, but you need to put in 2010-1900.

If you retrieve the time from the system and convert to a struct tm with something like localtime, you don't need to do any subtraction though, because what it puts into the struct tm is already the year - 1900. You do need to subtract 1900 when you fill in the year "manually".

Jerry Coffin
Ahh i understand now, i was populating the tm* struct manually, but i had been used to system filling the tm* struct for me. This makes sence, now i shall just put in 110 when manually filling the struct and i will get the proper date, cheers Jerry
paultop6
A: 

Looks like currentstruct->tm_year is 2010, which does mean a date in the year 3910. To make it correct, so it indicates a date in this year instead, you'll have to do a

currentstruct->tm_year -= 1900;

There's no way to tell strftime (or other system functions) that your struct tm is not really a struct tm because it's following different conventions than the system imposes (e.g., you want to have years starting from 0 rather than from 1900).

Alex Martelli