timegm cross platform

前端 未结 5 1001
忘了有多久
忘了有多久 2020-12-06 16:55

I\'m using Visual Studio c++ Compiler ( 2010 ), but the library has different implementation of ANSI C and POSIX libraries function.

What is the difference betw

5条回答
  •  难免孤独
    2020-12-06 17:31

    // Algorithm: http://howardhinnant.github.io/date_algorithms.html
    int days_from_civil(int y, int m, int d)
    {
        y -= m <= 2;
        int era = y / 400;
        int yoe = y - era * 400;                                   // [0, 399]
        int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;  // [0, 365]
        int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;           // [0, 146096]
        return era * 146097 + doe - 719468;
    }
    
    time_t timegm(tm const* t)     // It  does not modify broken-down time
    {
        int year = t->tm_year + 1900;
        int month = t->tm_mon;          // 0-11
        if (month > 11)
        {
            year += month / 12;
            month %= 12;
        }
        else if (month < 0)
        {
            int years_diff = (11 - month) / 12;
            year -= years_diff;
            month += 12 * years_diff;
        }
        int days_since_1970 = days_from_civil(year, month + 1, t->tm_mday);
    
        return 60 * (60 * (24L * days_since_1970 + t->tm_hour) + t->tm_min) + t->tm_sec;
    }
    

    This is a portable way to convert tm in UTC to time_t.

    Note that it does not modify/normalise tm structure and it does not change any tz settings.

提交回复
热议问题