Incorrect conversion to unix timestamp

I have a function that I wrote (if there is a good standard substitute, please let me know ...)

time_t get_unix_time(string time_str) {
    time_t loctime;
    time(&loctime);

    struct tm *given_time;
    time_str = time_str.substr(0, time_str.find_first_of('.'));

    replace(time_str.begin(), time_str.end(), ':', ',');
    replace(time_str.begin(), time_str.end(), '-', ',');
    replace(time_str.begin(), time_str.end(), '/', ',');
    replace(time_str.begin(), time_str.end(), ' ', ',');

    given_time = localtime(&loctime);
    vector<string> trecord = split_string(time_str, ',');

    given_time->tm_year = atoi(trecord.at(0).c_str()) - 1900;
    given_time->tm_mon  = atoi(trecord.at(1).c_str()) - 1;
    given_time->tm_mday = atoi(trecord.at(2).c_str());
    given_time->tm_hour = atoi(trecord.at(3).c_str());
    given_time->tm_min  = atoi(trecord.at(4).c_str());
    given_time->tm_sec  = atoi(trecord.at(5).c_str());

    return mktime(given_time);
}

The input (time_str) to the function has the format 1970-01-01 00: 00: 00.0 . The split_string () function splits a string time_strinto a vector containing:

{1970, 01, 01, 00, 00, 00}

which is used to populate the given_time structure.

I wrote a function to test it and passed exactly this input (the beginning of an era). However, the time it returns to me is 21600, which is 1970-01-01 06:00:00 , or UTC + 6 . The expected exit is 0 (the beginning of an era).

: -, UTC - 6. 1 1970 , @UTC 1 1970 06:00:00.

- , ? - - , , , UTC.

+3
6

glibc, timegm, mktime, GMT. , , . , .

+5

mktime . , 1970-01-01 00:00:00 , 1970-01-01 06:00:00 UTC, .

timegm, glibc. glibc, UTC mktime, TZ, mangmail:

time_t my_timegm (struct tm *tm) {
    time_t ret;
    char *tz;
    tz = getenv("TZ");
    setenv("TZ", "", 1);
    tzset();
    ret = mktime(tm);
    if (tz)
        setenv("TZ", tz, 1);
    else
        unsetenv("TZ");
    tzset();
    return ret;
}

, localtime , , , given_time->tm_isdst, .

+4

, gmtime time, .

Edit: , , . :

time_t get_unix_time(const string& time_str)
{
    vector<string> trecord = split_string(time_str, ',');

    tm given_time;
    given_time.tm_year = atoi(trecord.at(0).c_str()) - 1900;
    given_time.tm_mon  = atoi(trecord.at(1).c_str()) - 1;
    given_time.tm_mday = atoi(trecord.at(2).c_str());
    given_time.tm_hour = atoi(trecord.at(3).c_str());
    given_time.tm_min  = atoi(trecord.at(4).c_str());
    given_time.tm_sec  = atoi(trecord.at(5).c_str());

    return mktime(&given_time);
}

:

Ugh, mktime . , , UTC.

+1

. POSIX , time_t "" (1970-01-01 00:00:00 GMT) - leapsecond ( 86400 , SI ), .

, , , , .

, , , ISO C POSIX ​​, , , , - , GMT .

+1

mktime, . "localtime", , , .

0

strptime, .

struct tm given_time;

strptime(time_str.c_str(), "%Y-%m-%d %H:%M:%S", &given_time);

return mktime(&given_time);

@ Josh Kelley .

0

Source: https://habr.com/ru/post/1785238/


All Articles