c++ - 将带有 DST 的时间字符串转换为 UTC 时间戳

标签 c++ timezone mbed mktime

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

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

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

time_t current_time(void)
{
    time_t epoch = 0;
    parser.send("AT+CCLK?");
    string resp = read_until("OK\r\n");
    //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("\"\r\n");
    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 偏移量调整之前。

关于c++ - 将带有 DST 的时间字符串转换为 UTC 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720754/

相关文章:

c++ - Blowfish 仅使用 key 的第一个字符进行加密/解密

java - 将 GMT 转换为 BST Java

ssl - 为什么 nodeMCU tls mbed 库从 Pushbullet API 服务器收到错误 40(握手失败)?

c++ - 从 C++ 函数返回整个自定义类型数组

c++ - 使用 memset 将其设置为 0 后字符串数组不可用

c++ - 如何释放包含 std::vector 的对象的内存

c++ - 在erlang和c++之间发送数据

c++ - 魔兽世界模拟器 C++ 每 X 分钟预定事件

go - 获取完整的 UTC 偏移量格式

java - 在引入时区之前正确的时区是什么?