开发者

strftime doesnt display year correctly

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 c开发者_StackOverflow中文版orrect 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


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.


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".


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜