Mag*_*off 5 c++ boost-date-time
如何获取当前UTC偏移量(如时区,但只是当前时刻的UTC偏移量)?
我需要一个像"+02:00"这样的答案.
Mag*_*off 15
这个问题分为两部分:
boost::posix_time::time_durationtime_duration指定的显然,在广泛实施的API中,获取本地时区并未得到很好的体现.但是,我们可以通过取相对于UTC的时刻和相对于当前时区的相同时刻来获得它,如下所示:
boost::posix_time::time_duration get_utc_offset() {
using namespace boost::posix_time;
// boost::date_time::c_local_adjustor uses the C-API to adjust a
// moment given in utc to the same moment in the local time zone.
typedef boost::date_time::c_local_adjustor<ptime> local_adj;
const ptime utc_now = second_clock::universal_time();
const ptime now = local_adj::utc_to_local(utc_now);
return now - utc_now;
}
Run Code Online (Sandbox Code Playgroud)
根据指定格式化偏移量只需要灌输权利time_facet:
std::string get_utc_offset_string() {
std::stringstream out;
using namespace boost::posix_time;
time_facet* tf = new time_facet();
tf->time_duration_format("%+%H:%M");
out.imbue(std::locale(out.getloc(), tf));
out << get_utc_offset();
return out.str();
}
Run Code Online (Sandbox Code Playgroud)
现在,get_utc_offset_string()将产生预期的结果.