在linux下,若想使用 struct tm 从一个字符串中获取时刻秒数,则必须初始化。
下面的示例代码,在服务器中运行时,tmTime 的值会出现不为1595410483 的情况,导致程序处理出错。
struct tm when;
time_t tmTime = 0;
std::string strTime = "2020-07-22 17:34:43";
sscanf(strTime.data(), "%d-%d-%d %d:%d:%d", &when.tm_year, &when.tm_mon, &when.tm_mday, &when.tm_hour, &when.tm_min, &when.tm_sec);
when.tm_mon -= 1;
when.tm_year -= 1900;
tmTime = mktime(&when);
应改为下列示例
struct tm when;
time_t tmTime = 0;
localtime_r(&tmTime,&when);
std::string strTime = "2020-07-22 17:34:43";
sscanf(strTime.data(), "%d-%d-%d %d:%d:%d", &when.tm_year, &when.tm_mon, &when.tm_mday, &when.tm_hour, &when.tm_min, &when.tm_sec);
when.tm_mon -= 1;
when.tm_year -= 1900;
tmTime = mktime(&when);