我正在撰寫一種方法來決議各種格式的日期/時間字串。
std::chrono::system_clock::time_point toTimePoint(const std::string str) {
... a bunch of code that determines the format of the input string
std::string formatStr = string{"%Y-%m-%d"}
" " // Delimeter between date and time.
"%H:%M:%S"
"%t%Z"
;
// The %t should be 0 or 1 whitespace
// The %Z should be a timezone name
std::chrono::system_clock::time_point retVal;
std::istringstream in{str};
in >> date::parse(formatStr, retVal);
return retVal;
}
然后我用各種輸入對其進行測驗。其他格式有效。我可以做到這些:
2022-04-01 12:17:00.1234
2022-04-01 12:17:00.1234-0600
2022-04-01 12:17:00.1234-06:00
后兩者適用于美國山區夏令時。它做所有正確的事情。第一個顯示為 12:17:00 UST。另外兩個是 18:17:00 UST。作業很棒。為簡潔起見,我省略了所有這些代碼。什么不起作用是這樣的:
2022-04-01 12:17:00.1234 US/Central
在撰寫了一個不同的程式來轉儲霍華德圖書館已知的時區名稱后,我嘗試了各種時區名稱。它們都不重要。我得到一個沒有時區偏移的 UST 時間值。
幸運的是,我現在需要的是 -06:00 格式,所以我可以繼續前進。但我想修復代碼,因為我們還有其他地方使用時區名稱,我想讓它正常作業。
我不確定我做錯了什么。
uj5u.com熱心網友回復:
%z當使用(例如)讀取偏移量時-0600,結合sys_time諸如 的型別system_clock::time_point,決議時間點被解釋為本地時間,并且根據sys_time前兩個示例中的需要應用偏移量來獲取 。
然而,當讀取時區名稱或縮寫時,情況并非如此%Z(注意從小寫 z 到大寫 Z 的變化)。
%Z決議時區縮寫或名稱,它只是一個字串。常見的情況是只決議一個縮寫,例如 CST。通常,從縮寫到偏移沒有唯一的映射。因此無法在內部應用偏移量。因此,決議值應始終解釋為本地時間。
然而,一切都沒有丟失。您可以將時區名稱決議%Z為字串,然后使用該名稱查找time_zone并使用它將決議local_time轉換為sys_time. 這可能看起來像:
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
istringstream in{"2022-04-01 12:17:00.1234 US/Central"};
string tz_name;
local_time<microseconds> local_tp;
in >> parse("%F %T%t%Z", local_tp, tz_name);
system_clock::time_point tp = locate_zone(tz_name)->to_sys(local_tp);
cout << tp << '\n';
}
只需string在呼叫中添加 a 作為第三個引數parse,并確保第一個引數是 alocal_time而不是 a sys_time。然后使用locate_zone獲取 atime_zone const*并呼叫to_sys它,傳入決議的local_time.
上述程式輸出:
2022-04-01 17:17:00.123400
這比 -6h 偏移量減少了一個小時,因為美國/中部在 2022-03-13(-5h 偏移量)進入夏令時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448021.html
下一篇:計算資料幀中具有分鐘差異的連續行
