我想根据程序运行的时间创建带有时间戳的文件名,即
logfile_2020-04-21_18:11:10.txt
logfile_2020-04-22_18:13:43.txt
...
我可以获取时间戳(我认为)
std::chrono::steady_clock::time_point timestamp = std::chrono::steady_clock::now();
但我不知道如何将其转换为字符串,更不用说人类可读的字符串了。
时间戳的确切格式并不重要,只要它具有完整的日期和时间即可。有没有一种简单的方法可以使用标准库在 C++ 中执行此操作?
最佳答案
您所要求的内容尚未定义。您的时间戳来自“稳定”时钟 which guarantees monotonic time but is not related to wall clock time and thus cannot be converted into a human-readable timestamp (想想如果你将系统时间调整-1分钟会发生什么,单调时钟永远不能这样调整!)。单调时钟通常从系统启动时开始计数。如果您想打印时间戳,您最有可能想要使用 std::chrono::system_clock
- 例如像这样:
#include <iostream>
#include <chrono>
#include <iomanip>
int main() {
auto timestamp = std::chrono::system_clock::now();
std::time_t now_tt = std::chrono::system_clock::to_time_t(timestamp);
std::tm tm = *std::localtime(&now_tt);
std::cout << std::put_time(&tm, "%c %Z") << '\n';
return 0;
}
您可以在 std::put_time()
documentation 中找到有关格式化日期/时间的更多信息。 .
警告: std::localtime
可能不是线程安全的!如果您打算在多线程上下文中使用标准库,请检查它的文档。有时还提供可重入版本(通常称为 localtime_r
)。
关于c++ - 创建人类可读的时间戳并存储在 C++ 中的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646576/