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

C++中获取可传入_mkgmtime()的tm结构体本地时间,解决localtime不安全问题

可用的安全函数及示例

因为localtime()使用静态分配的struct tm缓冲区,存在线程安全问题和数据覆盖风险,所以编译器会标记它为不安全。你可以用以下两个安全替代函数来获取本地时间并填充struct tm,之后传入_mkgmtime():

1. localtime_s(Windows/MSVC环境)

这是微软实现的安全版本,要求你传入自己分配的struct tm指针,避免静态缓冲区的问题。函数原型为:

errno_t localtime_s(struct tm* _Tm, const time_t* _Time);

使用示例:

#include <time.h>
#include <stdio.h>

int main() {
    time_t current_time = time(NULL);
    struct tm local_tm;

    // 填充本地时间到自定义的tm结构体
    errno_t err = localtime_s(&local_tm, &current_time);
    if (err != 0) {
        printf("Failed to retrieve local time\n");
        return 1;
    }

    // 将本地时间的tm结构体转换为GMT时间戳
    time_t gmt_timestamp = _mkgmtime(&local_tm);
    if (gmt_timestamp == -1) {
        printf("Failed to convert local time to GMT\n");
        return 1;
    }

    printf("GMT timestamp: %lld\n", (long long)gmt_timestamp);
    return 0;
}

2. localtime_r(POSIX系统:Linux/macOS等)

这是POSIX标准定义的线程安全版本,同样需要传入自己分配的struct tm,函数原型为:

struct tm* localtime_r(const time_t* timep, struct tm* result);

使用示例:

#include <time.h>
#include <stdio.h>

int main() {
    time_t current_time = time(NULL);
    struct tm local_tm;

    // 填充本地时间到自定义的tm结构体
    if (localtime_r(&current_time, &local_tm) == NULL) {
        printf("Failed to retrieve local time\n");
        return 1;
    }

    // 注意:_mkgmtime是Windows特有函数,类Unix系统通常用标准库函数实现类似逻辑,若需跨平台需封装
    time_t gmt_timestamp = _mkgmtime(&local_tm);
    if (gmt_timestamp == -1) {
        printf("Failed to convert local time to GMT\n");
        return 1;
    }

    printf("GMT timestamp: %lld\n", (long long)gmt_timestamp);
    return 0;
}

关键注意点

  • _mkgmtime是Windows专属函数,作用是将**本地时间的struct tm**转换为GMT时间戳(和mktime相反,mktime是把本地tm转本地时间戳)。
  • 跨平台开发时,建议通过条件编译区分系统,选择对应的安全函数(localtime_s或localtime_r)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:10:28