编程语言
首页 > 编程语言> > C/C++ mktime 不符合预期

C/C++ mktime 不符合预期

作者:互联网

#include <time.h>

#include <chrono>
#include <iostream>
#include <string>

int main() {
    time_t now = time(nullptr); //获取UTC时间
    tm local_tm_now;
    if (localtime_r(&now, &local_tm_now) == nullptr) {
        return 1;
    }
    const time_t local_now = std::mktime(&local_tm_now); //得到当地日历时间
    tm local_tm_create;

    std::string str_time = "20210209101004";
    if (strptime(str_time.c_str(), "%Y%m%d%H%M%S", &local_tm_create) == nullptr) {
        return 2;
    }
    if (difftime(local_now, std::mktime(&local_tm_create)) >= 1800) {
        return 3; // GCC10 GLIBC2.29 will return here
    }

    return 0; // GCC4 GLIBC2.21 will return here
}

解决方法:
tm local_tm_create.tm_isdst = 0;

https://stackoverflow.com/questions/25374877/mktime-function-of-libc-returns-different-values-for-the-same-input

标签:return,C++,mktime,tm,time,符合,now,local
来源: https://www.cnblogs.com/stdpain/p/14392606.html