gpt4 book ai didi

C++ time() 给我几乎随机的结果

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:19 24 4
gpt4 key购买 nike

我写了如下简单的代码:

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

似乎如果我删除 time() 函数 - 它工作得更好,但在该代码之后我需要它。

最佳答案

您应该设置 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

关于C++ time() 给我几乎随机的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37050680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com