如何直接从字符串初始化std::chrono::gps_clock?GCC14下的疑问
关于std::chrono::gps_clock从字符串初始化的问题解答
这是预期行为吗?
是的,这属于标准库的预期行为。std::chrono::from_stream在解析时间字符串到gps_time时,默认会将输入的字符串视为UTC时间,然后自动完成UTC到GPS时间的转换。
截至2024年,GPS时间比UTC时间快18秒(累计闰秒差值),所以解析UTC的2024-01-01 00:00:00后,转换为GPS时间就会加上这18秒,最终得到2024-01-01 00:00:18。
如何直接从字符串初始化gps_clock?
目前C++20/23的标准库中,from_stream没有提供直接将字符串解析为GPS时间的格式选项,但可以通过以下简便方法实现:
先将字符串解析为通用的系统时间点(如sys_seconds),再提取该时间点的time_since_epoch()时长,直接用这个时长构造gps_time——这样相当于告诉程序,输入的字符串本身就是GPS时间的日历点,无需进行UTC到GPS的转换。
示例代码:
#include <iostream> #include <sstream> #include <string> #include <chrono> int main(int argc, char **argv) { // 先解析为系统时间点(仅提取日历时间对应的时长) std::chrono::sys_seconds temp_tp; std::stringstream neededGPSTime("2024-01-01 00:00:00"); std::chrono::from_stream(neededGPSTime, "%F %T", temp_tp); // 用提取的时长直接构造GPS时间 std::chrono::gps_time<std::chrono::seconds> GPS{temp_tp.time_since_epoch()}; std::cout << "Needed GPS Time: " << neededGPSTime.str() << std::endl << "Time of GPS variable: " << GPS << std::endl; return 0; }
运行该代码会输出:
Needed GPS Time: 2024-01-01 00:00:00 Time of GPS variable: 2024-01-01 00:00:00
如果需要更高精度(如毫秒、微秒),只需将sys_seconds替换为对应精度的sys_time(如std::chrono::sys_time<std::chrono::milliseconds>),同时gps_time也使用相同精度即可。
内容的提问来源于stack exchange,提问作者Johannes
相关产品推荐
相关产品推荐

