Skip to content

getEpochTime/localtime referenced to 1900, not 1970? #89

Open
@jackthese

Description

@jackthese

The documentation says:

NTPClient/README.md

Lines 51 to 52 in 0664e67

## Function documentation
`getEpochTime` returns the Unix epoch, which are the seconds elapsed since 00:00:00 UTC on 1 January 1970 (leap seconds are ignored, every day is treated as having 86400 seconds). **Attention**: If you have set a time offset this time offset will be added to your epoch timestamp.

However, to get the correct year I must add 1900 to my timenow.tm_year, not 1970.

When I run this sketch:

#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);
}

I get this output:

2020-01-04 2:38:04
2020-01-04 2:38:09
2020-01-04 2:38:14

[...]

Is there some subtlety I'm missing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: documentationRelated to documentation for the projecttype: imperfectionPerceived defect in any part of project

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions