通过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;
}