1

When using ESP8266 - getting seconds from epoch is done using

NTP.begin(NTPserver, 2, true);
delay(delay_tries);
time_t t = now();

while t stores amount of seconds from 1-1-1970.

When trying to do the same, using ESP32 - I cant get that numeric representation.

code below is from ESP32 example- updating time using NTP server ( process is done correct ). BUT when using now() yields 1970, as if NTP update has never occured.

How can I get time from Epoch ?

#include <WiFi.h>
#include "time.h"
#include <TimeLib.h>    <------- Added to original Code

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

void setup()
{
  Serial.begin(115200);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
  Serial.println(now());   <-------- Added to original code
}
  • where is now() defined or even used in the code you posted? – Jaromanda X Jan 4 at 1:32
  • Does your code output "Failed to obtain time"? – Jaromanda X Jan 4 at 1:48
  • try time(nullptr) instead of now() - since now() is not even a valid function in the code you posted – Jaromanda X Jan 4 at 1:55
  • you can use the NTP library on ESP32 and you can use the SDK time functions on esp8266 too – Juraj Jan 4 at 7:03
  • 1
    @Guy.D - just because you added now() to the code you've shown, doesn't make it valid (if I try to use now() in ESP32 code, it doesn't even compile :p – Jaromanda X Jan 4 at 18:14
2

to return 'epoch' seconds there is a function time in time.h

time_t now;
time(&now);

time_t is defined as long

this time is retrieved by the ESP32 SDK from NTP servers configured with ESP32 Arduino function configTime

EDIT: it is the standard C time() function

  • 2
    since time also returns a time_t you can use it like now() ... i.e. time(nullptr); – Jaromanda X Jan 4 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.