I have obtained the time via NTP with the correct daylight savings offset included.
configTime(0, 0, ntpServerName); // *** this sets up the clock to sync with your chosen NTP server/pool.
Serial.println(F("Setting TZ env"));
delay(500);
setenv("TZ", "GMT0BST,M3.5.0/2,M10.5.0/2", 1); // *** this is setup for UK daylight savings rules. You can look up your required TZ string online
tzset();
while (!time(nullptr))
{
Serial.println(F("Waiting for time.h"));
delay(500);
}
Serial.println("Time Initialized");
…however when I then try to extract the hour using TimeLib.h functions, it appears to return the hour without the 1H offset included.
Since you know if it is DST or not from the NTP call, your code needs an if statement that tests the NTP DST and adjusts the Timelib function as appropriate.
Do a successful compile, now select the library TimeLib and right click, select Goto Definition. Do you see any DST functions?
Remember, DST is highly variable; you need Lat/Lon as well. There are numerous small towns, counties, and even an entire Canadian Province that do NOT use DST. I think there are also US states. I have no idea about the rest of the world.
We were supposed to get rid of this dumb idea several years ago but so far they can't seem to manage it.
As long as I can remember the UK has been going to get rid of this dumb idea. I've no doubt that long after I'm gone the UK will be going to get rid of this dumb idea.
The Time library uses TimeLib.h, used to be Time.h but that caused confusion with the standard time.h library on file systems that are not case sensitive.
+1
Time libraries with DST calculations are now included in ESP board files.
No extra libraries or code needed.
Just enter the correct location string, found on this site.
This is the only line needed for TZ and DST. configTzTime("GMT0BST,M3.5.0/1,M10.5.0", "uk.pool.ntp.org"); // London
Leo..
This is the absolute minimum needed for an ESP32 to get internet time.
Unlike the sketch in post#16, it does not wait for a valid timestring on startup.
Leo..
#include <WiFi.h> // ESP32
unsigned long prevTime;
time_t now; // holds epoch
tm tm; // time struct
void setup() {
Serial.begin(115200);
WiFi.begin("SSID", "PASS"); // WiFi credentials
configTzTime("GMT0BST,M3.5.0/1,M10.5.0", "uk.pool.ntp.org"); // London
}
void loop() {
time(&now);
if (now != prevTime) { // if time (in seconds) has changed
prevTime = now; // remember
localtime_r(&now, &tm); // convert epoch to local time
printf("%02u:%02u:%02u\n", tm.tm_hour, tm.tm_min, tm.tm_sec);
}
}
Edit: more time elements are available to print, like year, day, date, month summer/winter, etc.