Time library functions with ESP32 core

bperrybap:
Have you properly set up the TZ variable?

I had to do that as well:

  if (Year < 2020)
  {
    if (Serial.available() > 0)
    {
      // read in the user input
      Day = Serial.parseInt();
      Month = Serial.parseInt();
      Year = Serial.parseInt();
      Hour = Serial.parseInt();
      Minute = Serial.parseInt();
      Second = Serial.parseInt();
      boolean validDate = (inRange(Day, 1, 31) && inRange(Month, 1, 12) && inRange(Year, 2021, 2031));
      boolean validTime = (inRange(Hour, 0, 23) && inRange(Minute, 0, 59) && inRange(Second, 0, 59));
      if (validTime && validDate)
      {
        configTime(0, 0, "pool.ntp.org");    // Repair timezone
        setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 3);
        tzset();
        
        struct tm t;                         //Prepare time strucure
        time_t t_of_day;
        t.tm_year = Year - 1900; // Year - 1900
        t.tm_mon = Month - 1;     // Month, where 0 = jan
        t.tm_mday = Day ;      // Day of the month
        t.tm_hour = Hour;
        t.tm_min = Minute;
        t.tm_sec = Second;
        t.tm_isdst = -1;         // Is DST on? 1 = yes, 0 = no, -1 = unknown
        t_of_day = mktime(&t);
        Console3.printf("Epoch = %10lu",t_of_day);
        struct timeval tv;                   //Extending to mandatory microseconds
        tv.tv_sec = t_of_day;  // epoch time (seconds)
        tv.tv_usec = 0;    // microseconds
        settimeofday(&tv, 0);                //Setting Clock
      }
    }
  }

Man! was that clumsy!

At GitHub they told me to load the Time.lib from Paul Stoffregen, what I personally consider to be a VERY BAD idea. That Arduino library has some differences with the built in library from the ESP and -to my experience- creates on the ESP more problems, than it solves.

You can set the timezone string and the ntp servers with a single call.
on the esp32 the prototype is:

void configTzTime(const char* tz, const char* server1, const char* server2, const char* server3)

where server2 and server3 are optional.
Code is here:

On the esp8266 it is a different name using an overload for configTime()

The Time library is actually by Michael Margolis. Paul just hosts it and somewhat maintains it.
Even though it doesn't have proper timezone support. It can be useful, especially if you muck with the time_t to trick it into thinking the local time is GMT.
It also uses a 64 bit unsigned time_t vs a 32 bit signed time_t

the esp8266 and esp32 time code will break in 17 years in 2038 as the time_t rolls over.

--- bill

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.