Getting time,date,month,year from NTP server using ESP32

In the following code,
the last line is Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
This prints day of week, month of year, day of month, year, hour, minutes, seconds in the Serial Monitor. But I don't want to print this on the serial monitor. Rather I need the integer value of year, month,day, hour, minute for further calculations. Is there any function from where I can get those values from NTP server and store them in integer variables?

#include <WiFi.h>
#include "time.h"

const char* ssid       = "SSID_NAME";   //Replace with your own SSID
const char* password   = "YOUR_PASSWORD";  //Replace with your own password

const char* NTPServer = "pool.ntp.org";
const long  GMTOffset_sec = 3600;   //Replace with your GMT offset (seconds)
const int   DayLightOffset_sec = 0;  //Replace with your daylight offset (seconds)

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 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()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

That information is stored as integers in the 'tm' struct. See 'time.h':

struct tm
{
  int	tm_sec;
  int	tm_min;
  int	tm_hour;
  int	tm_mday;
  int	tm_mon;
  int	tm_year;
  int	tm_wday;
  int	tm_yday;
  int	tm_isdst;
#ifdef __TM_GMTOFF
  long	__TM_GMTOFF;
#endif
#ifdef __TM_ZONE
  const char *__TM_ZONE;
#endif
};

1 Like

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