将具有 DST 的时间字符串转换为 UTC 时间戳

Convert a time string with DST to UTC timestamp

本文关键字:转换 UTC 时间戳 字符串 时间 DST      更新时间:2023-10-16

我正在尝试将已设置为具有DST的特定时区(例如德黑兰+4.30/3.30(的人类可读时间字符串转换为UTC时间戳。我在STM设备上使用ARM mbed-os平台,该设备缺少一些C时间函数,如strptime

无论如何,我将时间字符串转换为时间戳,但我不知道如何将其更改为 UTC。字符串时间是为具有 DST 的特定时区设置的,因此我不能简单地添加/删除时区差距。

我也更喜欢将时区作为我的current_time函数的参数,这样我就可以在不同的时区使用它。

time_t current_time(void)
{
    time_t epoch = 0;
    parser.send("AT+CCLK?");
    string resp = read_until("OKrn");
    //result would be something like this:
    /*
    +CCLK: "19/06/23,19:33:42+18"
    OK
    */
    // extract time string
    unsigned int pos = resp.find("+CCLK: "");
    unsigned int pos2 = resp.rfind(""rn");
    if ((pos != string::npos) && (pos2 != string::npos))
    {
        string time_str = resp.substr(pos + 8, pos2 - pos - 11);
        //convert to timestamp
        int hh, mm, ss, yy, mon, day;
        struct tm when = {0};
        sscanf(time_str.c_str(), "%d/%d/%d,%d:%d:%d", &yy, &mon, &day, &hh, &mm, &ss);
        when.tm_hour = hh;
        when.tm_min = mm;
        when.tm_sec = ss;
        when.tm_year = 2000 + yy - 1900;
        when.tm_mon = mon - 1;
        when.tm_mday = day;
        epoch = mktime(&when);
        // below doesn't work all time because we have DST
        // add 3.30 (+1.00 daylight) offset to get UTC
        epoch = epoch - (time_t)((4 * 3600) + (30 * 60));
    }
    return epoch;
}

尝试:

when.tm_isdst = -1;

在调用 mktime 之前,并删除 epoch UTC 偏移量调整。