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;
}
相关推荐
鹏大师运维3 小时前
为什么信创电脑装软件总提示“软件包架构不匹配”?
linux·运维·架构·国产化·麒麟·deb·统信uos
fqbqrr3 小时前
2606C++,C++构的多态
开发语言·c++
小欣加油4 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
Yolo_TvT5 小时前
C++:析构函数
c++
鹤落晴春5 小时前
【Linux复习】管理SELinux安全性
linux·运维·服务器
yz_aiks5 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
Hello:CodeWorld6 小时前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
bjzhang757 小时前
CentOS下安装MySQL详解
linux·mysql·centos
Jason_chen8 小时前
Linux 6.2 音频机制深度解析:AI驱动的低延迟音频与零信任音频安全架构
linux
下午写HelloWorld8 小时前
Linux系统及Ubuntu常用指令
linux·ubuntu·操作系统