C++ 计算当前时区偏移量秒数(GMT/UNIX偏移量)

通过BOOST

#include <boost/date_time/posix_time/posix_time.hpp>

#include <boost/date_time/local_time/local_time.hpp>

cpp 复制代码
                boost::posix_time::ptime localTime = boost::posix_time::second_clock::local_time();
                boost::posix_time::time_duration gmtOffset = localTime - boost::posix_time::second_clock::universal_time();
                return gmtOffset.total_seconds();

通过C标准库

cpp 复制代码
#include <stdio.h>
#include <time.h>

#ifdef _WIN32
#include <Windows.h>

#define localtime_r(t, res) localtime_s(res, t)
#define gmtime_r(t, res) gmtime_s(res, t)
#endif

int get_utc_offset() {
                time_t t = time(NULL);

                struct tm local_tm;
                struct tm gmt_tm;

                localtime_r(&t, &local_tm);
                gmtime_r(&t, &gmt_tm);

                struct tm* local = &local_tm;
                struct tm* gmt = &gmt_tm;

                int hour_diff = local->tm_hour - gmt->tm_hour;
                int min_diff  = local->tm_min - gmt->tm_min;

                if (local->tm_yday > gmt->tm_yday) 
                {
                    hour_diff += 24;
                }
                else if (local->tm_yday < gmt->tm_yday) 
                {
                    hour_diff -= 24;
                }
            
                return hour_diff * 3600 + min_diff * 60;
}
相关推荐
Yyyy4821 天前
Ubuntu安装Jenkis
linux·运维·ubuntu
Larry_Yanan1 天前
Qt多进程(一)进程间通信概括
开发语言·c++·qt·学习
zhuzewennamoamtf1 天前
Linux SPI设备驱动
android·linux·运维
春日见1 天前
在虚拟机上面无法正启动机械臂的控制launch文件
linux·运维·服务器·人工智能·驱动开发·ubuntu
J ..1 天前
C++ 多线程编程基础与 std::thread 使用
c++
你的冰西瓜1 天前
C++标准模板库(STL)全面解析
开发语言·c++·stl
松涛和鸣1 天前
Linux Makefile : From Basic Syntax to Multi-File Project Compilation
linux·运维·服务器·前端·windows·哈希算法
闻缺陷则喜何志丹1 天前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
chen_ever1 天前
Protobuf详解(从安装到实战)
c++·rpc·信息与通信
Predestination王瀞潞1 天前
JDK安装及环境变量配置
java·linux·开发语言