商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++时间格式化输出方法详解

C++时间格式化输出方法详解

  发布于2025-10-06 阅读(0)

扫一扫,手机访问

使用C++格式化时间需结合chrono、ctime与strftime函数,先获取当前时间戳并转为本地tm结构,再用strftime按%Y-%m-%d %H:%M:%S等格式输出到缓冲区,推荐使用std::array防溢出。

c++中如何格式化时间输出_c++时间格式化输出方法

在C++中格式化时间输出,通常使用标准库中的 chronoctime 头文件配合 strftime 函数来实现。下面介绍几种常用方法,帮助你将时间以指定格式输出,比如 "2024-05-30 14:30:00" 这样的形式。

获取当前时间并转换为本地时间

要格式化输出时间,先要获取当前时间点,并将其转换为可读的结构化时间(struct tm):

使用 std::time 获取当前时间戳,再用 std::localtime 转换为本地时间结构。

include <iostream>

include <ctime>


int main() {
    std::time_t now = std::time(nullptr);
    std::tm* localTime = std::localtime(&now);

    // 接下来可以格式化输出
}

使用 strftime 格式化时间

strftime 是C风格函数,功能强大,支持多种格式控制符,能将 tm 结构格式化为字符串。

常见格式控制符:

  • %Y - 四位年份(如 2024)
  • %m - 月份(01-12)
  • %d - 日期(01-31)
  • %H - 小时(00-23)
  • %M - 分钟(00-59)
  • %S - 秒数(00-60)
  • %F - 等价于 %Y-%m-%d(ISO 日期格式)
  • %T - 等价于 %H:%M:%S

include <iostream>

include <ctime>

include <array>


int main() {
    std::time_t now = std::time(nullptr);
    std::tm* localTime = std::localtime(&now);

    std::array<char, 100> buffer;
    std::size_t len = std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);

    if (len != 0) {
        std::cout << "当前时间: " << buffer.data() << std::endl;
    }

    return 0;
}

输出示例:
当前时间: 2024-05-30 14:30:00

C++11 chrono 高精度时间结合格式化

如果你使用的是 C++11 或更高版本,可以用 std::chrono 获取高精度时间,但最终仍需转为 time_t 才能用 strftime 格式化。

include <iostream>

include <chrono>

include <ctime>

include <array>


int main() {
    auto now = std::chrono::system_clock::now();
    std::time_t time_t = std::chrono::system_clock::to_time_t(now);
    std::tm* localTime = std::localtime(&time_t);

    std::array<char, 100> buffer;
    std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", localTime);

    std::cout << "格式化时间: " << buffer.data() << std::endl;

    return 0;
}

这种方式更现代,适合需要高精度时间记录的场景。

基本上就这些。掌握 std::timestd::localtimestrftime 的组合使用,就能灵活输出任意格式的时间字符串。注意缓冲区大小避免溢出,推荐使用 std::arraystd::string 配合动态长度检查。不复杂但容易忽略细节。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注