2016-05-05 19 views
2

我写了下面的简单代码: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 

看来,如果我删除时间()函数 - 它的作品更好,但我最需要它的代码之后。

回答

1

您应该设置DST标志。它可能正在随机初始化

如果夏令时有效,夏令时标志(tm_isdst)大于零,如果夏令时无效,则为零;如果信息不可用,则小于零。

http://www.cplusplus.com/reference/ctime/tm/

一个有用的配方以拳头与当前本地时间初始化tm结构,使这一被设置方式与你的机器上一切一样。

time_t now = time(0); 
uts_time = * localtime(&now); 
// initialise with the time you really want 
+0

如何正确使用? :) – JavaRunner

+0

你能展示它在我的代码中的样子吗?因为我得到:候选函数(隐式复制赋值运算符)不可行:对于第一个 参数,没有从“struct tm *”到“const tm”的已知转换;用* – JavaRunner

+0

取消引用参数对不起,忘了从本地时间取消引用返回。回答编辑 – ravenspoint

1

你有你的tm结构的某些未初始化的部分:上回读任何未初始化的部分行为是不确定

改为使用类似tm foo{};的代码,这会导致所有结构元素初始化为零值(以及指向空指针值的指针)。

+0

'tm uts_time {}'给我:*错误:预期';'在宣言结束时* – JavaRunner

+0

你忘了';'? – Bathsheba

+1

这会造成混乱,如果他目前在DST – ravenspoint