我写了一个简单的代码:
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();'
。
为什么我有不同的可读时间&#34;如果我不改变代码中的任何内容?
输出:
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()函数 - 它工作得更好但我需要在代码之后。
答案 0 :(得分: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
答案 1 :(得分:1)
您的tm
结构中有一些未初始化的部分:回读任何未初始化部分时的行为未定义。
使用类似tm foo{};
的代码,这会导致所有结构元素都被初始化为零值(以及指向空指针值的指针)。