Clang 17无法找到<format>,如何将std::chrono时间点转为字符串?
解决方法
针对你遇到的Clang 17在Linux下无法找到<format>的问题,这里提供几种不依赖std::format的实现方式,同时保留std::chrono时间点的使用:
方法一:使用Boost.Format + Boost.DateTime
这是你允许的方案,需要引入Boost库的DateTime和Format模块:
#include <boost/date_time/posix_time/posix_time.hpp> #include <boost/format.hpp> #include <chrono> #include <string> int main() { std::chrono::high_resolution_clock::time_point tp = std::chrono::high_resolution_clock::now(); // 注意:部分系统中high_resolution_clock可能与system_clock不同步,需先转换为system_clock时间点 auto sys_tp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(tp); std::time_t sys_time = std::chrono::system_clock::to_time_t(sys_tp); // 转换为Boost的ptime对象,支持高精度格式化 boost::posix_time::ptime boost_tp = boost::posix_time::from_time_t(sys_time); // 补充微秒部分(如果需要更高精度) auto micros = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()) % 1000000; boost_tp += boost::posix_time::microseconds(micros.count()); // 使用Boost.Format格式化字符串,格式符与std::format兼容 std::string formatted = (boost::format("%Y-%m-%d %H:%M:%S.%f") % boost_tp).str(); // 若不需要微秒,改用格式串"%Y-%m-%d %H:%M:%S"即可 return 0; }
编译时需链接Boost的相关库,比如:clang++ -std=c++2b your_code.cpp -lboost_date_time -lboost_format
方法二:手动转换+strftime(无第三方库依赖)
如果不想引入Boost,可以用标准库的strftime结合字符串拼接实现,同时处理高精度部分:
#include <chrono> #include <string> #include <ctime> #include <sstream> #include <iomanip> int main() { std::chrono::high_resolution_clock::time_point tp = std::chrono::high_resolution_clock::now(); // 处理时钟同步问题:若high_resolution_clock是steady_clock别名,需计算与system_clock的偏移 auto sys_now = std::chrono::system_clock::now(); auto high_now = std::chrono::high_resolution_clock::now(); auto offset = sys_now - std::chrono::time_point_cast<std::chrono::system_clock::duration>(high_now); auto sys_tp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(tp) + offset; // 转换为time_t并格式化日期时间部分 std::time_t t = std::chrono::system_clock::to_time_t(sys_tp); char time_buf[20]; std::strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&t)); // 拼接高精度部分(微秒) std::ostringstream oss; oss << time_buf << "." << std::setw(6) << std::setfill('0') << std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count() % 1000000; std::string formatted = oss.str(); // 不需要高精度的话直接用time_buf即可 return 0; }
编译时无需额外链接库:clang++ -std=c++2b your_code.cpp
注意事项
- 部分Linux系统中
std::chrono::high_resolution_clock是std::chrono::steady_clock的别名,其epoch是程序启动时间而非UTC时间,因此必须计算与system_clock的偏移才能得到正确的日历时间。 - 如果你的系统中
high_resolution_clock与system_clock是同一时钟(比如多数x86_64系统),可以省略偏移计算步骤。
内容的提问来源于stack exchange,提问作者intrigued_66
相关产品推荐
相关产品推荐

