How to convert a UTC date & time to a time_t in C++?

前端 未结 4 988
一整个雨季
一整个雨季 2021-01-05 03:26

I want to convert a UTC date & time given in numbers for year, month, day, etc. to a time_t. Some systems offer functions like mkgmtime or timegm

4条回答
  •  太阳男子
    2021-01-05 04:06

    For completeness, here's a version of mkgmtime() that takes a struct tm* as argument:

    static time_t mkgmtime(const struct tm *ptm) {
        time_t secs = 0;
        // tm_year is years since 1900
        int year = ptm->tm_year + 1900;
        for (int y = 1970; y < year; ++y) {
            secs += (IsLeapYear(y)? 366: 365) * SecondsPerDay;
        }
        // tm_mon is month from 0..11
        for (int m = 0; m < ptm->tm_mon; ++m) {
            secs += DaysOfMonth[m] * SecondsPerDay;
            if (m == 1 && IsLeapYear(year)) secs += SecondsPerDay;
        }
        secs += (ptm->tm_mday - 1) * SecondsPerDay;
        secs += ptm->tm_hour       * SecondsPerHour;
        secs += ptm->tm_min        * SecondsPerMinute;
        secs += ptm->tm_sec;
        return secs;
    }
    

提交回复
热议问题