首页 > 解决方案 > esp32 使用的 c++ 库中的纪元以来的时间

问题描述

我正在尝试创建一个库c++以供 esp32 使用,并可能在 linux 或 windows 中使用。

现在,我有一段代码以毫秒为单位获取自纪元以来的时间,这是 1970 年 1 月 1 日。这在 linux 中完美运行。虽然,当 esp32 运行此代码时,它会返回自程序启动以来的时间。可能我的问题的根源是我正在使用的库chrono,使用方法millis(),如果是arduino,它会返回程序启动以来的时间。

milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

c++我的问题是,有没有什么方法可以在所有平台上工作的代码中获得自纪元以来的正确时间?

标签: c++timechronoesp32

解决方案


我设法通过使用宏来修复它:

#if defined(ESP32) 
const char* ntpServer = "pool.ntp.org"; 
const long gmtOffset_sec = 0; 
const int daylightOffset_sec = 3600; 
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); 
#endif

这样 esp32 可以从 ntpServer 获取时间,而不是获取程序启动后的时间。


推荐阅读