簡體   English   中英

如何使用 std::put_time 和 std::chrono 以 H:M:S 格式正確顯示時間

[英]How to correctly display the time in the H:M:S format with std::put_time and std::chrono

我正在嘗試使用 std::chrono 測量函數的時間。 但是時間沒有正確輸出。 由於某種原因增加了 3 小時。

我的代碼

auto begin = std::chrono::steady_clock::now();
    
for (int i = 0; i < 5; i++) { Sleep(1000); }

auto end = std::chrono::steady_clock::now();

const std::time_t total = std::chrono::duration_cast<std::chrono::seconds>(end - begin).count();

std::stringstream ssTotal;

ssTotal << std::put_time(std::localtime(&total), "%H:%M:%S");

輸出總計:03:00:05

問題是std::time_t用於時間點而不是持續時間,然后當您通過std::localtime傳遞它時,它會嘗試考慮您的本地時區。

“正確”的答案是一直堅持持續時間,但 AFAIK 好的格式化和打印內容是尚未廣泛實現的 C++20 功能。

一個快速的解決方法是使用std::gmtime而不是std::localtime ,因為它會調整到 +0 時區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM