【问题标题】:Convert a time string with DST to UTC timestamp将带有 DST 的时间字符串转换为 UTC 时间戳
【发布时间】:2019-06-23 03:22:13
【问题描述】:

我正在尝试将已设置为具有 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("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;
}

【问题讨论】:

  • 它是 arm mbed 平台,它应该具有 c++ 定义。不过我更喜欢用C,不过能不能用对我来说无所谓。

标签: c++ timezone mbed mktime


【解决方案1】:

试试:

when.tm_isdst = -1;

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

【讨论】:

  • 谢谢,但我怎么知道当前时间是为特定时区设置的(例如当前时间已设置为德黑兰 (+3.30))?
  • 我的建议取决于您的计算机将其当前时区设置设置为“亚洲/德黑兰”。如果不是这种情况,则没有纯 std C 或 C++ 解决方案。但是,如果您对此感兴趣,我确实有一个 C++11(和转发)第 3 方库可以完成这项工作。
  • 我找到了this,但做的却与我想要的相反。
  • 我以某种方式通过使用手动转换来修复它,但我接受了这个问题,因为它让我了解了问题所在。
猜你喜欢
  • 2015-04-20
  • 2019-10-29
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多