c++ 获取当前时间的字符串

创建日期: 2024-09-27 11:16 | 作者: 风波 | 浏览次数: 14 | 分类: C++

来源:chatGPT

#include <iostream>
#include <chrono>
#include <iomanip>
#include <ctime>

std::string getCurrentTime(std::string fmt) {
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();

    // 转换为时间_t
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);

    // 转换为 tm 结构
    std::tm now_tm = *std::localtime(&now_c);

    // 格式化时间为字符串
    std::ostringstream oss;
    oss << std::put_time(&now_tm, fmt.data());

    return oss.str();
}

int main() {
    std::string currentTime = getCurrentTime("%Y-%m-%d %H:%M:%S");
    std::cout << "当前时间: " << currentTime << std::endl;
    return 0;
}
14 浏览
9 爬虫
0 评论