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;
}
相关推荐
木心月转码ing10 小时前
WSL+Cpp开发环境配置
linux
端平入洛1 天前
auto有时不auto
c++
崔小汤呀1 天前
最全的docker安装笔记,包含CentOS和Ubuntu
linux·后端
何中应1 天前
vi编辑器使用
linux·后端·操作系统
何中应1 天前
Linux进程无法被kill
linux·后端·操作系统
何中应1 天前
rm-rf /命令操作介绍
linux·后端·操作系统
何中应1 天前
Linux常用命令
linux·操作系统
葛立国1 天前
从 / 和 /dev 说起:Linux 文件系统与挂载点一文理清
linux
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc