【发布时间】:2010-08-17 17:49:11
【问题描述】:
我需要以这种格式 yyyymmdd 生成时间戳。基本上我想创建一个具有当前日期扩展名的文件名。 (例如:log.20100817)
【问题讨论】:
我需要以这种格式 yyyymmdd 生成时间戳。基本上我想创建一个具有当前日期扩展名的文件名。 (例如:log.20100817)
【问题讨论】:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char date[9];
time_t t = time(0);
struct tm *tm;
tm = gmtime(&t);
strftime(date, sizeof(date), "%Y%m%d", tm);
printf("log.%s\n", date);
return EXIT_SUCCESS;
}
【讨论】:
tm 临时值 - 您可以将 gmtime(&t) 的返回值直接传递给 strftime()。
gmtime 返回的内容。通常你不会只打印它。
另一种选择:Boost.Date_Time。
【讨论】:
现代C++ 答案:
#include <iomanip>
#include <sstream>
#include <string>
std::string create_timestamp()
{
auto current_time = std::time(nullptr);
tm time_info{};
const auto local_time_error = localtime_s(&time_info, ¤t_time);
if (local_time_error != 0)
{
throw std::runtime_error("localtime_s() failed: " + std::to_string(local_time_error));
}
std::ostringstream output_stream;
output_stream << std::put_time(&time_info, "%Y-%m-%d_%H-%M");
std::string timestamp(output_stream.str());
return timestamp;
}
所有格式代码在std::put_time页面上都有详细说明。
【讨论】: