C++ 时间字符串的格式化输出

第一种方法,使用 ctime 库

// #include <ctime>  
// #include <iomanip>  
std::string formatTime(const std::time_t& time, const char* format) {
    std::tm tm;
#ifdef _WIN32
    ::localtime_s(&tm, &time);
#else
    ::localtime_r(&tm, &time);
#endif
    char buffer[80];
    std::strftime(buffer, sizeof(buffer), format, &tm);
    return std::string(buffer);
}

2.使用 chrono 和 put_time 格式化字符串

// #include <chrono>
// #include <sstream>
std::string formatTimePoint(const std::chrono::system_clock::time_point& time_point,
    const std::string& format = "%Y-%m-%d %X")
{
    auto in_time_t = std::chrono::system_clock::to_time_t(time_point);
    std::tm tm;
#ifdef _WIN32
    ::localtime_s(&tm, &in_time_t);
#else
    ::localtime_r(&tm, &in_time_t);
#endif
    std::stringstream ss;
    ss << std::put_time(&tm, format.c_str());
    return ss.str();
}

使用方法如下:

int main()
{
  // 方法一
  std::time_t now1 = std::time(nullptr); // 获取当前时间   
  std::string formattedTime = formatTime(now1, "%Y-%m-%d %H:%M:%S"); // 使用指定的格式输出时间 
  std::cout << "Formatted time1: " << formattedTime << std::endl;
  // 方法二
  const std::chrono::time_point<std::chrono::system_clock> now2 = std::chrono::system_clock::now();
  std::cout << "Formatted time2: " << formatTimePoint(now2) << std::endl;
  return 0;
}

结果输出:

2022-03-25 12:17:57
2022-03-25 12:17:57

Process finished with exit code 0

在C++中,标准库 ctime 的 std::strftime 函数并不直接支持毫秒级别的格式化。但是,可以使用 chrono 库来获取毫秒,并将其手动添加到格式化后的时间字符串中。

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

int main() {
    // 获取当前时间(包括毫秒)  
    auto now = std::chrono::system_clock::now();
    auto time_t_now = std::chrono::system_clock::to_time_t(now);

    // 将 std::time_t 转换为 struct tm  
    std::tm tm;
#ifdef _WIN32
    ::localtime_s(&tm, &time_t_now);
#else
    ::localtime_r(&tm, &time_t_now);
#endif

    // 创建一个足够大的字符数组来存储格式化后的时间字符串  
    char time_str[80];

    // 使用 strftime 来格式化时间(不包含毫秒)  
    std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", &tm);

    // 获取毫秒部分  
    auto duration_since_epoch = now.time_since_epoch();
    auto millis_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(duration_since_epoch);
    int milliseconds = millis_since_epoch.count() % 1000; // 只需要毫秒部分  

    // 创建一个字符串流来拼接毫秒  
    std::ostringstream oss;
    oss << time_str << "." << std::setfill('0') << std::setw(3) << milliseconds;

    // 输出格式化后的时间字符串(包含毫秒)  
    std::cout << "Formatted time with milliseconds: " << oss.str() << std::endl;

    return 0;
}
posted @   卡尔的思索  阅读(1980)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示