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;
}
相关推荐
都小事儿17 小时前
U-boot:自搬移
linux·spring boot
星火开发设计17 小时前
C++ multimap 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识
JiMoKuangXiangQu18 小时前
Linux 内存 domain 管理
linux·内存管理·domain
warton8818 小时前
ubuntu24下操作配置mysql8相关目录到指定地址
linux·运维·mysql
小亮亮虫18 小时前
linux-交叉编译链安装
linux
学Linux的语莫18 小时前
本地部署ollama
linux·服务器·langchain
`林中水滴`18 小时前
Linux系列:Linux 安装 MySQL 5.7.27 教程
linux·mysql
m0_7381207218 小时前
应急响应——知攻善防蓝队溯源靶机Linux-2详细流程
linux·服务器·网络·安全·web安全·php
李日灐18 小时前
C++STL:deque、priority_queue详解!!:详解原理和底层
开发语言·数据结构·c++·后端·stl
散人102418 小时前
Linux(Ubuntu)RIME 中文输入法-朙月拼音
linux·ubuntu·rime