文章详情
C++获取当前时间文本
Posted on 2022-02-28 18:34:53 by 主打一个C++
#include <iostream>
#include <ctime>
#include <iomanip>
// 定义函数,用于获取当前时间文本
std::string getCurrentTimeText() {
// 获取当前时间的时间戳
std::time_t now = std::time(nullptr);
// 将时间戳转换为本地时间结构
std::tm* localTime = std::localtime(&now);
// 创建一个用于拼接字符串的字符串流
std::ostringstream oss;
// 使用 std::put_time 将本地时间格式化为指定格式,并放入字符串流中
oss << std::put_time(localTime, "%Y-%m-%d %H:%M:%S");
// 返回格式化后的时间文本字符串
return oss.str();
}
int main() {
// 调用函数获取当前时间文本,并存储在 currentTime 变量中
std::string currentTime = getCurrentTimeText();
// 输出当前时间文本
std::cout << "当前时间为:" << currentTime << std::endl;
return 0;
}
*转载请注明出处:原文链接:https://cpp.vin/page/48.html