我写了下面的简单代码:C++时间()给我几乎是随机结果
time_t makeUnixTimeStamp(int year, int month, int day, int hour, int min, int sec) {
tm uts_time;
uts_time.tm_year = year - 1900;
uts_time.tm_mon = month - 1;
uts_time.tm_mday = day;
uts_time.tm_sec = sec;
uts_time.tm_min = min;
uts_time.tm_hour = hour;
return mktime(&uts_time);
}
std::string getReadableDateTime(unsigned int unixTimeStamp) {
char dateTime[ 40 ];
time_t someTime = unixTimeStamp;
struct tm *mTime;
mTime = localtime(&someTime);
strftime(dateTime, sizeof(dateTime), "%Y-%m-%d %H:%M:%S", mTime);
return std::string(dateTime);
}
unsigned int startLogTime = makeUnixTimeStamp(2016, 05, 04, 00, 00, 00);
time_t nowTime;
time(&nowTime);
std::cout << "readable Time = " << getReadableDateTime(startLogTime) << '\n';
我得到一些运行后怪输出。当前显示时间为php -r 'echo time();'
。 如果我不改变我的代码中的任何东西,为什么我有不同的“可读时间”?
输出:
15:20:58 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450865
15:21:05 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450866
15:21:06 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450867
15:21:07 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-03 23:00:00
1462450868
15:21:08 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-03 23:00:00
1462450869
15:21:09 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450871
15:21:11 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-03 23:00:00
1462450872
15:21:12 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450877
15:21:17 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-04 00:00:00
1462450882
15:21:22 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();'
readable Time = 2016-05-03 23:00:00
1462450883
看来,如果我删除时间()函数 - 它的作品更好,但我最需要它的代码之后。
如何正确使用? :) – JavaRunner
你能展示它在我的代码中的样子吗?因为我得到:候选函数(隐式复制赋值运算符)不可行:对于第一个 参数,没有从“struct tm *”到“const tm”的已知转换;用* – JavaRunner
取消引用参数对不起,忘了从本地时间取消引用返回。回答编辑 – ravenspoint