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

为何std::gmtime未返回UTC时间?程序两次输出本地时间

问题原因及修正方案

你的代码出现两次输出本地时间的问题,核心原因有三个:

1. 未初始化时间戳变量

代码里直接使用了&current_time,但既没有定义time_t类型的current_time变量,也没有通过time()函数获取当前系统时间戳,这属于未定义行为,程序运行时的时间数据是随机的。

2. gmtime与localtime共享静态缓冲区

这两个函数的返回值都是指向同一个内部静态内存区域的指针。当你先调用gmtime写入UTC时间数据,再调用localtime时,后者会直接覆盖这个缓冲区里的内容,导致两个指针最终指向的都是本地时间的数据。

3. asctime同样依赖静态缓冲区

asctime会把格式化后的时间字符串写入另一个静态缓冲区,两次调用时后一次的结果会覆盖前一次,不过这里因为前面的tm数据已经被覆盖,所以最终两次输出都是本地时间。


修正后的代码

#pragma warning(disable : 4996)

#include <ctime>
#include <iostream>
using namespace std;

int main()
{
    // 初始化当前时间戳
    time_t current_time = time(nullptr);
    
    // 将gmtime的结果复制到自定义结构体,避免被覆盖
    tm utc_tm = *gmtime(&current_time);
    // 获取本地时间并复制
    tm local_tm = *localtime(&current_time);

    // 用自定义缓冲区存储格式化后的字符串,避免静态缓冲区覆盖
    char utc_time_str[26];
    char local_time_str[26];
    asctime_s(utc_time_str, sizeof(utc_time_str), &utc_tm);
    asctime_s(local_time_str, sizeof(local_time_str), &local_tm);

    cout << "Current UTC date and time: " << utc_time_str;
    cout << "Current local date and time: " << local_time_str;

    return 0;
}

关键修改说明:

  • 补充#include <iostream>:cout属于该头文件的内容,原代码缺失会导致编译错误。
  • 初始化time_t变量:通过time(nullptr)获取当前系统时间戳,确保时间数据有效。
  • 复制tm结构体:把gmtime和localtime返回的静态缓冲区内容复制到自定义的tm变量中,避免后续调用覆盖数据。
  • 使用asctime_s:这是asctime的安全替代版本,将格式化后的字符串写入你指定的缓冲区,彻底避免静态缓冲区覆盖问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:15:02