【发布时间】:2017-02-14 04:03:18
【问题描述】:
我有一个boost::posix_time::ptime 对象(Boost v1.60),它在系统的时区中有日期和时间信息。我需要将其转换为 UTC 中的 unix 时间戳。
time_t convertLocalPtimeToTimestamp(const boost::posix_time::ptime& pt)
{
using namespace boost::local_time;
static const time_t t_null = 0;
static struct tm* tm_local = localtime(&t_null);
static time_zone_ptr zone(new posix_time_zone(tm_local->tm_zone));
LOG(debug) << "Zone " << zone->to_posix_string();
local_date_time az(pt.date(), pt.time_of_day(), zone, local_date_time::EXCEPTION_ON_ERROR);
LOG(debug) << "local_date_time: " << az;
LOG(debug) << "local_time: " << az.local_time();
LOG(debug) << "utc_time: " << az.utc_time();
struct tm t = to_tm(az);
time_t ts = mktime(&t);
return ts;
}
我的情况(欧洲/马德里)的结果是:
Zone CET+00
local_date_time: 2016-Oct-05 17:36:27.701162 CET
local_time: 2016-Oct-05 17:36:27.701162
utc_time: 2016-Oct-05 17:36:27.701162
1475685387
这个结果有各种错误:
- 应将时区检测为夏令时:CEST (+0200) 而不是 CET (+0100)
- 即使没有 DST 检测,utc_time 也应该不同于 local_time。
- 最后,时间戳应该代表 UTC 时间,而不是本地时间。
任何帮助将不胜感激。
【问题讨论】:
-
Boost 在这方面很臭。你考虑过github.com/HowardHinnant/date
标签: c++ datetime boost timezone