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