将具有 DST 的时间字符串转换为 UTC 时间戳
Convert a time string with DST to UTC timestamp
我正在尝试将已设置为具有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 偏移量调整。
相关文章:
- 将具有 DST 的时间字符串转换为 UTC 时间戳
- 使用 std::chrono / date::gps_clock 将双 GPS 时间戳转换为 UTC/tai
- 如何将 UTC 时间戳转换为本地时间,即整点后的几秒钟
- 将 UTC 时差转换为字符串增强
- 将UTC tm*转换为本地化tm*的跨平台方式
- 跨平台C++:使用历史数据转换为 UTC/本地时间
- 从SYSTEMTIME到time_t的转换以UTC/GMT表示时间
- 使用UTC来回转换日期以忽略DST但仍使用当前用户的有效区域设置是否安全
- C++ 将包含 UTC 日期和时间的字符串转换为 TM 结构
- 将 UTC time_t转换为不同的时区C++线程安全
- 如何使用 WinAPI 可靠地将本地时间转换为 UTC C++ 在 Windows 计算机上
- 将 UTC 转换为本地
- 使用boost将UTC时间转换为自定义时区
- 将以字符串形式给出的时间(UTC)转换为本地时间
- 将UTC毫秒转换为人类可读日期时间
- 从GMT/UTC字符串到UNIX时间戳的Qt5(C++)转换
- 使用时间位置将日期时间从/转换为UTC时间戳
- 将服务器UTC时间转换为客户端本地时间
- 自unix epoch以来,将日期,时间和UTC偏移值转换为毫秒
- 将boost ptime从本地时间转换为UTC时间