【问题标题】:Time since epoch in c++ library used by esp32esp32 使用的 c++ 库中的纪元以来的时间
【发布时间】:2019-10-25 11:25:55
【问题描述】:

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

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

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

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

【问题讨论】:

  • 不是 1970 年以来的纪元秒数吗?您可以通过配置 SNTP github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/… 来获取时间
  • 我不明白你的问题。谢谢,我查看了它并设法获得了我所在区域的时间格式,但我真正想要的是自 1970 年 1 月 1 日午夜以来的毫秒数,这是 unix 纪元时间:)
  • 别介意Juraj。我使用宏修复了它:#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
  • @FilipeAmador,请不要将您的答案添加为评论,而是作为您问题的答案,以便您关闭它。这也将允许人们对您的答案进行投票

标签: c++ time chrono esp32


【解决方案1】:

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

#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 获取时间,而不是获取程序启动后的时间。

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2013-03-26
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2016-04-17
    • 2019-12-04
    • 2013-10-25
    相关资源
    最近更新 更多