Sync Time of ESP32 with NTP and set it as system time, and parse it in variable

This question relates to the use of TimeLib.h
Basically, I want to sync my time with the NTP server and set it as the default system time and then break whatever value is into variables that I can use in loops. I tried doing this with a few methods.

void printLocalTime(){
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}

and then

int tday = (*timeinfo, "%d") did not work.

int tday = timeinfo.tm_mday did not work

int tday = day() did not work

I tried using the default esp8266 example that comes with the library but that doesn't work with my esp32.

this example of unrelated library has it

1 Like

Look at this example and also check ESP32 System Time.

1 Like

I am assuming you are pointing me towards the part of the code that

time_t now = time(nullptr);
while (now < SECS_YR_2000) {
delay(100);
now = time(nullptr);
}
setTime(now);

After adding this code I did

Serial.println("Day today is is");
Serial.print(day()); The output is "1" meaning that it still thinks its day one
Serial.print("Day of Month: ");
Serial.println(&timeinfo, "%d"); Works perfectly

Since day () does not produce a value I cant save it in a variable and I cant do

int todayis = (&timeinfo, "%d");

I have gone through both the documentation and the example you have given The documentation shows to solution to my specific problem.

and speaking of example, it also does not show any solution.

They are getting the values by doing

struct tm timeinfo;
  if(!getLocalTime(&timeinfo))

and use

Serial.println(&timeinfo, "%d")

to get the day of the month. But how do i add it into a variable?

tm is a struct.
timeinfo your instance of the struct.
so you could use a

Serial.print(timeinfo.tm_mday); // day of month

to print or similar to assign to another variable. but what for? The value is available in the struct anyway.

here you find my working example of NTP for the ESP:
https://werner.rothschopf.net/microcontroller/202103_arduino_esp32_ntp_en.htm

1 Like

Thank you but I believe I am doing something very wrong but "Serial.print(timeinfo.tm_mday);" gave this error.

'struct tm' has no member named 'tm_day'

Basically, I am trying to create a loop that goes like this

if (day:month == day:montth+1){
     do stuff }
else {
     do other stuff }

so I need different parts of the time struct to perform this. I need to loop between a certain date that comes every month.

any chance that you just give the sketch from my page a try?
Does it compile?
Does it output the current time?

1 Like

Thank you for this. Has solved my problem for now. Hopefully, I can learn from this.

1 Like