如何在GCC13中从字符串初始化std::chrono::gps_clock变量
如何在GCC13中将字符串初始化std::chrono::gps_clock变量
核心思路
由于GCC13不支持std::chrono::parse和std::chrono::from_stream,我们可以通过手动解析时间字符串 + UTC与GPS时间的闰秒偏移转换来实现目标,具体步骤如下:
- 从固定格式的字符串中提取年、月、日、时、分、秒
- 将解析结果转换为UTC时区的
std::chrono::sys_time - 基于闰秒差值,将UTC时间转换为
gps_clock::time_point
实现代码
#include <chrono> #include <cstdio> #include <stdexcept> std::chrono::gps_clock::time_point gps_time_from_string(const char* time_str) { int year, month, day, hour, minute, second; // 解析ISO8601格式字符串(YYYY-MM-DDTHH:MM:SS) if (std::sscanf(time_str, "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute, &second) != 6) { throw std::invalid_argument("Invalid time string format"); } // 构造UTC时间点 using namespace std::chrono; sys_days utc_date = year_month_day{year, month(month), day(day)}; auto utc_time = utc_date + hours(hour) + minutes(minute) + seconds(second); // 截至2024年,UTC比GPS慢18秒(累计闰秒数) // 若需处理更早/更晚时间,需维护对应时间段的闰秒对照表 constexpr seconds gps_utc_offset{18}; auto gps_time = gps_clock::from_sys(utc_time + gps_utc_offset); return gps_time; } // 测试示例 int main() { try { auto gps_tp = gps_time_from_string("2024-08-09T22:20:50"); auto gps_sec = std::chrono::duration_cast<std::chrono::seconds>(gps_tp.time_since_epoch()).count(); printf("GPS time since epoch: %lld\n", gps_sec); } catch (const std::exception& e) { printf("Error: %s\n", e.what()); } return 0; }
关键细节说明
- 字符串解析:用
std::sscanf匹配固定格式,适合ISO8601这类结构规整的时间字符串,简单高效。 - UTC时间构造:
sys_days是C++17引入的类型,直接对应UTC日期,叠加时分秒后得到精确UTC时间点,避免时区干扰。 - 闰秒偏移逻辑:GPS时钟不考虑闰秒,因此GPS时间始终比UTC快,差值等于历史累计闰秒数。截至2024年该差值为18秒,若处理跨闰秒更新的时间范围,需动态维护闰秒对照表。
- 时间转换:
gps_clock::from_sys是GCC支持的原生方法,可直接将调整后的UTC时间转换为GPS时间点。
内容的提问来源于stack exchange,提问作者Johannes
相关产品推荐
相关产品推荐

