在C++中生成当前时间戳字符串
在C++中,你可以使用<chrono>和<ctime>库来获取当前时间并将其格式化为字符串。以下是几种实现方式:
方法1:使用C++11的<chrono>和<ctime>
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
std::string getCurrentTimestamp() {
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 转换为time_t以便使用C函数
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
// 转换为本地时间
std::tm local_tm = *std::localtime(&now_time);
// 使用stringstream格式化输出
std::ostringstream oss;
oss << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S");
return oss.str();
}
int main() {
std::string timestamp = getCurrentTimestamp();
std::cout << "当前时间戳: " << timestamp << std::endl;
return 0;
}
方法2:使用C风格的<ctime>函数
#include <iostream>
#include <ctime>
#include <iomanip>
#include <sstream>
std::string getCurrentTimestamp() {
std::time_t now = std::time(nullptr);
std::tm local_tm = *std::localtime(&now);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &local_tm);
return std::string(buffer);
}
int main() {
std::string timestamp = getCurrentTimestamp();
std::cout << "当前时间戳: " << timestamp << std::endl;
return 0;
}
方法3:使用C++20的<chrono>格式化功能(需要C++20支持)
#include <iostream>
#include <chrono>
#include <format>
std::string getCurrentTimestamp() {
auto now = std::chrono::system_clock::now();
return std::format("{:%Y-%m-%d %H:%M:%S}", now);
}
int main() {
std::string timestamp = getCurrentTimestamp();
std::cout << "当前时间戳: " << timestamp << std::endl;
return 0;
}
格式说明
在上述代码中,%Y-%m-%d %H:%M:%S是时间格式字符串,其中:
%Y- 四位数的年份%m- 两位数的月份(01-12)%d- 两位数的日期(01-31)%H- 24小时制的小时(00-23)%M- 分钟(00-59)%S- 秒(00-60)
你可以根据需要调整格式,例如:
"%Y%m%d_%H%M%S"→ 输出类似 "20231225_143022""%F %T"→ C++20简写,等同于"%Y-%m-%d %H:%M:%S"
选择哪种方法取决于你的C++版本和项目需求。方法1和方法2适用于C++11及以上,方法3需要C++20支持。

572

被折叠的 条评论
为什么被折叠?



