2010-10-04 35 views

回答

14

有两个部分对这个问题:

  1. 获得UTC偏移为boost::posix_time::time_duration
  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()将产生期望的结果。

+0

这是一个复杂的问题;例如,特定的UTC偏移量可以对应于多个时区。 – 2010-10-04 11:16:22

+0

@Roger:所以......我想说正确的方法是我正在寻找当前时间的UTC偏移量,而不是时区? – 2010-10-04 11:29:26

+1

是的,如果这就是你感兴趣的东西(这也是我听起来的样子),这个答案是现货。我更多地回应说:“让本地时区在广泛实施的API中暴露得并不好。”请注意,您今天获得的UTC偏移量可能稍后(或更早)会有所不同。 – 2010-10-04 11:31:37

1

由于C++ 11可以使用计时和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

相关问题