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
}
1 Answer 1
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
-
2since
time
also returns atime_t
you can use it likenow()
... i.e.time(nullptr);
Jaromanda X– Jaromanda X01/04/2020 16:24:53Commented Jan 4, 2020 at 16:24
now()
defined or even used in the code you posted?"Failed to obtain time"
?time(nullptr)
instead ofnow()
- sincenow()
is not even a valid function in the code you postednow()
to the code you've shown, doesn't make it valid (if I try to usenow()
in ESP32 code, it doesn't even compile :p