ESP8266 NodeMCU and NTP time

I am messing around with an ESP8266 and want the shortest way of getting the time from the internet and displaying it.
This is the shortest working example that I can find but it prints the time and date as :
Sat Jan 15 10:08:00 2022
I want to extract the hour(); and minute(); etc but I cant find a way. If I try Serial.print(hour); like I can when using an RTC sketch for example it says that 'hour is not declared in this scope.
I thought that the time.h library allowed (hour) etc?

#include <ESP8266WiFi.h>
#include <time.h>


const char* ssid = "*****";
const char* password = "*****";
const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 0;   //Replace with your GMT offset (seconds)
const int   daylightOffset_sec = 0;  //Replace with your daylight offset (seconds)

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

  //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();
}
void printLocalTime()
{
  time_t rawtime;
  struct tm * timeinfo;
  time (&rawtime);
  timeinfo = localtime (&rawtime);
  Serial.println(asctime(timeinfo));
  delay(1000);
}

Hello

Look the definition of struct tm here : esp8266/time.h at master · arduino/esp8266 · GitHub

Use timeinfo->tm_hour etc

Thank you guix

Any idea why the year displays as 2022 in the timeinfo display to 122 in the tm_year display?

It's offset from 1900, like in the C++ standard https://www.cplusplus.com/reference/ctime/tm/

I have added 1900 to the tm_year and now get 2022 :grinning:
Thank you guix

1 Like

there is no need to set the daylightOffset manually.
Set your timezone and let the ESP calculate if it is time to switch to DST.
Here I have a short example:
https://werner.rothschopf.net/202011_arduino_esp8266_ntp_en.htm

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.