【问题标题】:How do I get the current UTC offset (time zone)?如何获取当前的 UTC 偏移量(时区)?
【发布时间】:2010-10-04 10:48:15
【问题描述】:

如何获取当前的 UTC 偏移量(与时区一样,但只是当前时刻的 UTC 偏移量)?

我需要像“+02:00”这样的答案。

【问题讨论】:

    标签: c++ boost-date-time


    【解决方案1】:

    这个问题分为两部分:

    1. boost::posix_time::time_duration 形式获取UTC 偏移量
    2. 按指定格式设置time_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;
    }
    

    按照指定格式化偏移量只是灌输正确的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() 将产生所需的结果。

    【讨论】:

    • 这是一个复杂的问题;例如,特定的 UTC 偏移量可能对应于多个时区。
    • @Roger:所以......我想正确的说法是我正在寻找当前时间的 UTC 偏移量,而不是时区?
    • 是的,如果您对此感兴趣(这也是我听起来的样子),那么这个答案就是正确的。我更多地回应了“在广泛实施的 API 中没有很好地公开本地时区”。请注意,您今天获得的 UTC 偏移量稍后(或更早)可能会有所不同。
    • @Roger:我更新了我的问题以更准确。当然,您的评论仍然是关于“获取本地时区......”:)
    【解决方案2】:

    从 C++11 开始,您可以使用 chrono 和 std::put_time:

    #include <chrono>
    #include <iomanip>
    #include <iostream>
    int main ()
    {
    
      using sc = std::chrono::system_clock;
      auto tm = sc::to_time_t(sc::now());
    
      std::cout << std::put_time(std::localtime(&tm), "formatted time: %Y-%m-%dT%X%z\n");
    
      std::cout << "just the offset: " << std::put_time(std::localtime(&tm), "%z\n");
    
    }
    

    这会产生以下输出:

    格式化时间:2018-02-15T10:25:27+0100

    只是偏移量:+0100

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2017-07-17
      • 2016-05-07
      • 2013-10-15
      • 2014-01-09
      • 2015-06-16
      相关资源
      最近更新 更多