先说一下UTC: 它是协调世界时间,又称世界统一时间、世界标准时间、国际协调时间,简称UTC
UTC时间与本地时间关系:UTC +时间差=本地时间
如果UTC时间是 2015-05-01 00:00:00
那么北京时间就是 2015-05-01 08:00:00
解释:
116444736000000000
是从1601年1月1日0:0:0:000到1970年1月1日0:0:0:000的时间(单位100ns)
- 解析一串 133395047197220000 数字转成UTC时间和本地时间(两种方式)
cpp
/*QT方法解析*/
long long currentMSecs = 133395047197220000;
long long milliseconds =( long long )( currentMSecs- 116444736000000000) / 10000;
QDateTime f = QDateTime::fromMSecsSinceEpoch(milliseconds);
qDebug() << f.toUTC().toString("yyyy-MM-dd hh:mm:ss:zzz");//UTC的
qDebug() << f.toString("yyyy-MM-dd hh:mm:ss:zzz");//本地的时间
结果:
"2023-09-18 09:58:39:722"
"2023-09-18 17:58:39:722"
cpp
/*C/C++方法解析*/
long long currentMSecs = 133395047197220000;
long long milliseconds =( long long )( currentMSecs- 116444736000000000) / 10000;
std::time_t current_time = milliseconds / 1000;
// 转换成本地时间
std::tm* local_time = std::localtime(¤t_time);
// 输出年月日时分秒毫秒
std::cout<< "Local date and time: "<<std::endl ;
std::cout<< local_time->tm_year + 1900 << "-" << local_time->tm_mon + 1 << "-" << local_time->tm_mday << " "<<local_time->tm_hour << ":" << local_time->tm_min << ":" << local_time->tm_sec << "." <<(milliseconds % 1000) <<std::endl ;
std::cout << "UTC date and time: "<<std::endl ;
std::cout<< local_time->tm_year + 1900 << "-" << local_time->tm_mon + 1 << "-" << local_time->tm_mday << " "<<local_time->tm_hour - 8 << ":" << local_time->tm_min << ":" << local_time->tm_sec << "." <<(milliseconds % 1000)<<std::endl ;
结果:
Local date and time:
2023-9-18 17:58:39.722
UTC date and time:
2023-9-18 9:58:39.722
- 生成当前时间 UTC 十八位时间戳
cpp
/*QT生成方法*/
QDateTime t = QDateTime::currentDateTimeUtc();
qDebug() << t.toString("yyyy-MM-dd hh:mm:ss:zzz");
long long currentMSecs = t.currentMSecsSinceEpoch();
// 获取从1970-01-01 00:00:00到现在的秒数
currentMSecs =(currentMSecs * 10000 )+ 116444736000000000;
qDebug()<<currentMSecs;
结果:
"2023-09-18 09:58:39:719"
133395047197220000