C++20中如何将std::chrono::hh_mm_ss类型转换为字符串
方案1:使用C++20 std::format(最简便)
std::chrono::hh_mm_ss类型原生支持C++20的格式化库,直接调用即可:
#include <format> #include <string> // 转普通std::string std::string str = std::format("{:%T}", formatted); // %T格式符会自动匹配你转换时的精度,这里转成了毫秒就会自动带上毫秒部分 // 如果只需要时分秒不需要毫秒,可以用格式串"{:%H:%M:%S}" // 转宽字符串std::wstring std::wstring wstr = std::wformat(L"{:%T}", formatted); // 转C风格字符串,直接调用对应字符串的c_str()方法即可 const char* c_str = str.c_str(); const wchar_t* c_wstr = wstr.c_str();
方案2:手动拼接(兼容性最好,可自定义程度高)
如果你的编译环境对std::format支持不完善,可以直接取hh_mm_ss的公开成员手动拼接:
#include <sstream> #include <iomanip> #include <string> // 拼接std::string std::ostringstream oss; oss << std::setw(2) << std::setfill('0') << formatted.hours().count() << ":" << std::setw(2) << std::setfill('0') << formatted.minutes().count() << ":" << std::setw(2) << std::setfill('0') << formatted.seconds().count() << "." << std::setw(3) << std::setfill('0') << formatted.subseconds().count(); std::string str = oss.str(); // 拼接宽字符串std::wstring std::wostringstream woss; woss << std::setw(2) << std::setfill(L'0') << formatted.hours().count() << L":" << std::setw(2) << std::setfill(L'0') << formatted.minutes().count() << L":" << std::setw(2) << std::setfill(L'0') << formatted.seconds().count() << L"." << std::setw(3) << std::setfill(L'0') << formatted.subseconds().count(); std::wstring wstr = woss.str();
std::setw和std::setfill用于补前导0,确保个位数的时分秒也能显示为2位,符合hh:mm:ss的格式要求。
流操作直接输出不生效的原因
直接用<<运算符输出hh_mm_ss是C20才支持的特性,需要确保你的编译器开启了C20及以上的编译标准(GCC/Clang加-std=c++20编译参数,Visual Studio在项目设置中将C标准改为C20),同时已经包含了<chrono>头文件。如果仍有兼容问题,优先使用上面两种方案更稳定。
内容的提问来源于stack exchange,提问作者noah
相关产品推荐
相关产品推荐

