[英]How to convert chrono::seconds to string in HH:MM:SS format in C++?
我有一個 function,它接受第二個作為參數並返回 HH:MM:SS 格式的字符串。 沒有 std::chrono,我可以這樣實現它:
string myclass::ElapsedTime(long secs) {
uint32_t hh = secs / 3600;
uint32_t mm = (secs % 3600) / 60;
uint32_t ss = (secs % 3600) % 60;
char timestring[9];
sprintf(timestring, "%02d:%02d:%02d", hh,mm,ss);
return string(timestring);
}
使用std::chrono
,我可以將參數轉換為std::chrono::seconds sec {seconds};
.
但是我怎樣才能將它轉換為具有格式的字符串呢? 我在https://youtu.be/P32hvk8b13M看到了來自 Howard Hinnant 的精彩視頻教程。 不幸的是,沒有這種情況的例子。
使用Howard Hinnant 的 header-only date.h 庫它看起來像這樣:
#include "date/date.h"
#include <string>
std::string
ElapsedTime(std::chrono::seconds secs)
{
return date::format("%T", secs);
}
如果你想自己寫,那么它看起來更像:
#include <chrono>
#include <string>
std::string
ElapsedTime(std::chrono::seconds secs)
{
using namespace std;
using namespace std::chrono;
bool neg = secs < 0s;
if (neg)
secs = -secs;
auto h = duration_cast<hours>(secs);
secs -= h;
auto m = duration_cast<minutes>(secs);
secs -= m;
std::string result;
if (neg)
result.push_back('-');
if (h < 10h)
result.push_back('0');
result += to_string(h/1h);
result += ':';
if (m < 10min)
result.push_back('0');
result += to_string(m/1min);
result += ':';
if (secs < 10s)
result.push_back('0');
result += to_string(secs/1s);
return result;
}
在 C++20 中,你可以說:
std::string
ElapsedTime(std::chrono::seconds secs)
{
return std::format("{:%T}", secs);
}
一旦 C++20 實現落地,您將能夠執行以下操作(未經測試的代碼):
std::chrono::hh_mm_ss<std::chrono::seconds> tod{std::chrono::seconds(secs)};
std::cout << tod;
有關詳細信息,請參閱time.hms.overview 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.