You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中获取仅含时分秒的系统时间(不含日期)

无指针获取当前时分秒的实现方案

方案一:用C++标准库的chrono与安全时间转换(无指针)

不需要依赖指针,通过C++11引入的<chrono>库获取当前时间,再用安全的时间转换函数写入本地的tm结构体实例:

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

int main() {
    // 获取当前系统时间的时间戳
    auto now = std::chrono::system_clock::now();
    std::time_t timestamp = std::chrono::system_clock::to_time_t(now);

    // 创建tm结构体实例,避免使用指针
    std::tm local_time{};
    // 跨平台安全转换:Windows用localtime_s,Linux/macOS用localtime_r
    #ifdef _WIN32
        localtime_s(&local_time, &timestamp);
    #else
        localtime_r(&timestamp, &local_time);
    #endif

    // 格式化输出时分秒(补零对齐)
    std::cout << std::setw(2) << std::setfill('0') << local_time.tm_hour << ":"
              << std::setw(2) << std::setfill('0') << local_time.tm_min << ":"
              << std::setw(2) << std::setfill('0') << local_time.tm_sec << std::endl;
    return 0;
}

这里的核心是自己创建tm对象,用安全函数把时间数据写入其中,全程不需要使用返回的指针,完全符合限制要求。

方案二:用系统命令直接输出(无交互)

如果想用类似system("time")的方式,修改命令就能避免输入交互:

  • Windows系统用time /t,只输出时分秒
  • Linux/macOS用date +%T,同样只输出时分秒

代码示例:

#include <cstdlib>

int main() {
    #ifdef _WIN32
        system("time /t");
    #else
        system("date +%T");
    #endif
    return 0;
}

这个方法简单快捷,但依赖操作系统,跨平台需要做条件编译。

内容的提问来源于stack exchange,提问作者senna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:25:19