Search code examples
c++timec++-chronoesp32

Time since epoch in c++ library used by esp32


I'm trying to create a library in c++ to be used by an esp32 and possibly to be used in linux or windows.

Right now, I have a piece of code that gets the time since epoch in millisecounds, this is 1 january 1970. This works perfectly in linux. Although, when the esp32 runs this code it returns the time since the program started. Probabily the source of my problem is that the library I'm using, chrono, uses the method millis(), which in case of the arduino returns the time since the program started.

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

My question is, is there any way of getting the correct time since epoch in c++ code that works in all the platforms ?


Solution

  • I managed to fixed it by using the macro:

    #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
    

    This way the esp32 can get the time from the ntpServer instead of getting the time since the program started.