timegm cross platform

笑着哭i 提交于 2019-11-28 11:59:22

I use the following macro on Windows:

#define timegm _mkgmtime

as _mkgmtime does the same.

When David Cutler's team started on the Windows NT design, back in 1989, they didn't yet know which api was going to be dominant. So they created three of them. Win32 was an adaption of the 16-bit version of the Windows api. OS/2 was supported, the operating system that was supposed to supplant DOS but didn't. And Posix was the third, added because the USA government back then specified that they would only consider using operating systems that followed the emerging Posix standard.

The tzset() function you mention is a left-over from the Posix api. You probably misspelled putenv(), same story. The subsystem didn't fare well, Win32 won the api battle in a big way and Posix support was removed from Windows in 2001. Microsoft kept the support for the Posix functions but renamed them with a leading underscore since they are not part of the standard C library. You are supposed to get deprecation warnings when you use the non-prefixed version of the functions. Sounds like you #defined _CRT_NONSTDC_NO_DEPRECATE to suppress them. Best to not do that. Favor the standard C library functions.

For most functions, that I know of, there is no difference.

The underscore in the names is there to emphasize that these are not standard C functions: AFAIK, there are not tzset nor setenv functions in ANSI C. They are mostly POSIX functions that are implemented by the MS CRT as an aid for portability from other operating systems.

But they don't claim POSIX compatibility, that's why the underscore. And that's why you should be careful and read the MS documentation about these functions... there are demons there!

Siewca

My implementation of timegm is working on windows.

time_t timegm(struct tm * a_tm)
{
    time_t ltime = mktime(a_tm);
    struct tm tm_val;
    gmtime_s(&tm_val, &ltime);
    int offset = (tm_val.tm_hour - a_tm->tm_hour);
    if (offset > 12)
    {
        offset = 24 - offset;
    }
    time_t utc = mktime(a_tm) - offset * 3600;
    return utc;
}

Should be fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!