5
A
回答
14
有兩個部分對這個問題:
- 獲得UTC偏移爲
boost::posix_time::time_duration
- 格式的
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()
將產生期望的結果。
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
相關問題
- 1. 當前時間= UTC +/-(UTC +/-當前時間)
- 2. 以UTC格式獲得UTC時區+/-
- 3. 如何計算當前UTC時間和其他UTC時間之間的差值?
- 4. 如何獲得NSDate和當前時間之間的時間差?
- 5. 如何在幾秒鐘內獲得當前UTC時間戳
- 6. 如何獲得給定時區的「午夜」的UTC時間?
- 7. 當前日期從UTC時區
- 8. 獲取基於時區和當前服務時間的時差
- 9. Perl獲取UTC時間並獲得UTC時間戳之間的差異
- 10. 如何禁用R警告:對象(UTC)的時區不同於當前時區()
- 11. 如何獲得當前時間和次日設定時間之間的時差?
- 12. 當我在golang中查詢mongodb時,如何獲得UTC時間
- 13. 獲取UTC與給定時區的小時差與Python
- 14. Android獲取當前UTC時間
- 15. Web服務獲取當前UTC時間?
- 16. MySQL UTC到當地時區
- 17. 如何使用獲得當前的時區和GMT
- 18. 如何從NSDate獲得當前時區的年月日
- 19. 如何獲得時區在Java中的當前日期偏移
- 20. Android如何獲得android中兩個時區之間的時差?
- 21. 如何獲取當地時區的當前日期和時間?
- 22. 如何比較UTC日期和Android中的當前UTC時間?
- 23. 如何從php iso utc中減去當前的utc時間?
- 24. 如何獲得mysql時間戳和php當前時間之間的差異?
- 25. MYSQL - 如何獲得時差?
- 26. 在動作中獲得當前UTC時間
- 27. 如何在Lua腳本中獲取當前的utc時間?
- 28. 如何使用Javascript獲取JSON格式的當前UTC時間?
- 29. 如何獲得當前時間戳
- 30. 如何獲得「當前系統時間」?
這是一個複雜的問題;例如,特定的UTC偏移量可以對應於多個時區。 – 2010-10-04 11:16:22
@Roger:所以......我想說正確的方法是我正在尋找當前時間的UTC偏移量,而不是時區? – 2010-10-04 11:29:26
是的,如果這就是你感興趣的東西(這也是我聽起來的樣子),這個答案是現貨。我更多地迴應說:「讓本地時區在廣泛實施的API中暴露得並不好。」請注意,您今天獲得的UTC偏移量可能稍後(或更早)會有所不同。 – 2010-10-04 11:31:37