【问题标题】:Create a human-readable timestamp and store in string in C++在 C++ 中创建人类可读的时间戳并存储在字符串中
【发布时间】:2020-08-22 02:05:45
【问题描述】:

我想根据程序运行的时间创建带有时间戳的文件名,即

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++ 中执行此操作的简单方法?

【问题讨论】:

标签: c++ chrono


【解决方案1】:

您要求的内容未定义。你的时间戳来自一个“稳定”的时钟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)。

【讨论】:

  • 完美,感谢您提供指向 put_time() 的链接。我正在寻找的格式是 std::put_time(&tm, "%Y-%m-%d_%H:%M:%S")。
猜你喜欢
  • 2013-12-14
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
相关资源
最近更新 更多