[英]portable way to create a timestamp in c/c++
I need to generate time-stamp in this format yyyymmdd.我需要以 yyyymmdd 格式生成时间戳。 Basically I want to create a filename with current date extension.基本上我想创建一个带有当前日期扩展名的文件名。 (for example: log.20100817) (例如: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;
}
另一种选择: Boost.Date_Time 。
A modern C++
answer:现代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;
}
All the format code are detailed on the std::put_time
page.所有格式代码都在std::put_time
页面上有详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.