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;
}
相关推荐
corpse201012 小时前
VirtualBox 安装ubuntu-25 ,配置SSH工具登录
linux·ubuntu·ssh
她说彩礼65万12 小时前
C语言 整形提升及算数转换
linux·服务器·c语言
RenPenry12 小时前
2026 在Linux上搭建CS2插件服务器
linux·运维·服务器·cs2·debian13
七点半77012 小时前
FFmpeg C++ AI视觉开发核心手册 (整合版)适用场景:视频流接入、AI模型预处理(抽帧/缩放/格式转换)、高性能算法集成。
c++·人工智能·ffmpeg
Deitymoon12 小时前
linux——TCP编程
linux·服务器
A.A呐12 小时前
【C++第二十八章】单例模式
c++·单例模式
云栖梦泽12 小时前
Linux内核与驱动:9.驱动中的中断机制
linux
格林威12 小时前
Windows 实时性补丁(RTX / WSL2)
linux·运维·人工智能·windows·数码相机·计算机视觉·工业相机
玖釉-12 小时前
C++ 硬核剖析:if 语句中的“双竖杠” || 到底怎么运行的?
开发语言·c++
xuxie9912 小时前
N22 key驱动
linux·运维·服务器