NTPClient
NTPClient copied to clipboard
getEpochTime/localtime referenced to 1900, not 1970?
My attached sketch works fine, but to get the correct year I must add 1900 to my timenow.tm_year, not 1970. Is there some subtilty I'm missing? Execution Output: 2020-01-04 2:38:04 2020-01-04 2:38:09 2020-01-04 2:38:14........
`#include <NTPClient.h> #include <WiFiUdp.h> // has variable type WiFiUDP, needed by timeClient() #include <time.h> // FYI: time.h simply calls timelib.h #include <stdio.h> // allows use of printf, among other things #ifdef ARDUINO_ARCH_ESP32 #include <WiFi.h> // library that works with ESP32 #endif #ifdef ESP8266 #include <ESP8266WiFi.h> // Library that works with ESP8266 #endif
const char *ssid = "XXXXXXXXXX"; const char *password = "YYYYYYYYYY";
WiFiUDP ntpUDP; long int gmtOffset = -8 * 3600; // Pacific Standard Time offset, seconds long int UpdateInterval = 1000 * 3600; // interval between calls to ntp, msec NTPClient timeClient(ntpUDP, "pool.ntp.org", gmtOffset, UpdateInterval); // set up time client
void setup() { Serial.begin(9600); Serial.printf("Connecting to %s with password %s\n", ssid, password); WiFi.begin(ssid, password); while ( WiFi.status() != WL_CONNECTED ) { delay ( 500 ); Serial.print ( "." ); } Serial.println("Connected"); timeClient.begin(); }
void loop() { timeClient.update(); // will call ntp only if needed, based on UpdateInterval time_t eptm; // C++ variable type, seconds since 1900 eptm = timeClient.getEpochTime(); // susposed to return sec since 1970, but magic here struct tm* timenow; // C++ structure to hold times timenow = localtime(&eptm); // function in time.h to get local time from time_t struct int Yr = 1900 + timenow->tm_year; // dig out Gregorian year. int Month = 1 + timenow->tm_mon; // dig out month; adjust to 1-12 range int DoM = timenow->tm_mday; int Hr = timenow->tm_hour; int Mn = timenow->tm_min; int Sc = timenow->tm_sec; Serial.printf("%4d-%02d-%02d %d:%02d:%02d\n", Yr, Month, DoM, Hr, Mn, Sc); delay(5000); }`
Hey there :) Thanks for the issue. Just a suggestion- try previewing the comment in markdown since your issue could be made more readable by having proper markdown for code. You can find guidelines to open an issue [here.] (https://github.com/arduino/Arduino/blob/master/CONTRIBUTING.md#issues)
I have replicated the above given code on an ESP8266. [Also, there were a few compilation errors kindly check for those and try inform those in as well while opening an issue] and I confirm that it is referenced at 1900 and not 1970. But, this is not a bug and a standard compliance instead.
The tm_year member of struct tm is relative to 1900 per the C library specification. All compliant standard libraries use that.
More on this- https://stackoverflow.com/questions/45355478/why-is-the-tm-year-member-in-struct-tm-relative-to-1900-rather-than-1970-in-c-on
I hope this helped @jackthese
I suggest closing this issue.