描述了如果通过时间戳获取对应的UTC及Local时间。
Linux提供了函数mktime用于完成反向操作,即通过时间值struct tm的数据结构获取其对应的时间戳time_t:
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int main(){
time_t ts = time(nullptr);
cout<<"ts1:"<<ts<<endl;
struct tm tUTC ,tLocal;
gmtime_r(&ts, &tUTC);
cout<<"ts2:"<<mktime(&tUTC)<<endl;
localtime_r(&ts, &tLocal);
cout<<"ts3:"<<mktime(&tLocal)<<endl;
return 0;
}
运行程序输出:
ts1:1661083240
ts2:1661054440
ts3:1661083240
需要注意的是ts2,也就是通过UTC的时间来获取的时间戳与ts1和ts3相差了28,800,也就是8x3600,即8个小时的时区。
这也说明mktime在返回时间戳的时候已经将本地的时区考虑了进去,也就是通过本地时间来计算的UTC时间。
所以如果那到的是UTC时间,需要对其计算的结果进行时区的加或减,才能得到正确的时间戳。