是否有跨平台的方法来获取 C++ 中的当前日期和时间?
原文由 Max Frai 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是获取时间戳的非弃用现代 C++ 解决方案 std::string
用于例如文件名:
std::string get_file_timestamp()
{
const auto now = std::chrono::system_clock::now();
const auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream output_stream;
struct tm time_info;
const auto errno_value = localtime_s(&time_info, &in_time_t);
if(errno_value != 0)
{
throw std::runtime_error("localtime_s() failed: " + std::to_string(errno_value));
}
output_stream << std::put_time(&time_info, "%Y-%m-%d.%H_%M_%S");
return output_stream.str();
}
原文由 BullyWiiPlaza 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
从 C++ 11 开始,您可以使用
std::chrono::system_clock::now()
示例(从 en.cppreference.com 复制):
这应该打印如下内容: