c++ QT 十八位时间戳转换

先说一下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)

  1. 解析一串 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(&current_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

  1. 生成当前时间 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

相关推荐
naruto_lnq21 小时前
分布式系统安全通信
开发语言·c++·算法
fen_fen21 小时前
Oracle建表语句示例
数据库·oracle
砚边数影1 天前
数据可视化入门:Matplotlib 基础语法与折线图绘制
数据库·信息可视化·matplotlib·数据可视化·kingbase·数据库平替用金仓·金仓数据库
orange_tt1 天前
Djiango配置Celery
数据库·sqlite
CSDN_RTKLIB1 天前
【四个场景测试】源文件编码UTF-8 BOM
c++
云小逸1 天前
【nmap源码学习】 Nmap网络扫描工具深度解析:从基础参数到核心扫描逻辑
网络·数据库·学习
肉包_5111 天前
两个数据库互锁,用全局变量互锁会偶发软件卡死
开发语言·数据库·c++
霖霖总总1 天前
[小技巧64]深入解析 MySQL InnoDB 的 Checkpoint 机制:原理、类型与调优
数据库·mysql
Trouvaille ~1 天前
【Linux】UDP Socket编程实战(一):Echo Server从零到一
linux·运维·服务器·网络·c++·websocket·udp
HellowAmy1 天前
我的C++规范 - 线程池
开发语言·c++·代码规范