如何获取当前UTC偏移量(时区)? [英] How do I get the current UTC offset (time zone)?
本文介绍了如何获取当前UTC偏移量(时区)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得当前UTC偏移量(如时区,但只是UTC偏移量的当前时刻)?
How do I get the current UTC offset (as in time zone, but just the UTC offset of the current moment)?
我需要一个答案像+ 02:00。
I need an answer like "+02:00".
推荐答案
此问题有两部分:
- 获取UTC偏移量为
boost :: posix_time :: time_duration
- code> time_duration 如指定
- Get the UTC offset as a
boost::posix_time::time_duration
- Format the
time_duration
as specified
,获得本地时区在广泛实现的API中不是很好地暴露。然而,我们可以通过取相对于UTC的时刻和相对于当前时区的相同时刻的差异来获得它,例如:
Apparently, getting the local time zone is not exposed very well in a widely implemented API. We can, however, get it by taking the difference of a moment relative to UTC and the same moment relative to the current time zone, like this:
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;
}
格式化指定的偏移只是一个充满正确的问题 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();
}
现在, get_utc_offset_string c>将产生所需的结果。
Now, get_utc_offset_string()
will yield the desired result.
这篇关于如何获取当前UTC偏移量(时区)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文