2010-10-04 37 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

相關問題