Set time in setup function using NTP?

I used this [0] post to create some working NTP code. It was very helpful. The issue I have now is that I want to set some flags before getting into the loop. Is there a way to get the time set during setup?

My Code : // code from:// https://forum.arduino.cc/t/getting-time-from-ntp-service-using - Pastebin.com

[0] Getting Time from NTP service using NODEMCU 1.0 (ESP- 12E) - #17 by thehrao

have you tried to put your while to the end of setup?

    while (time(nullptr) < 1617460172)  { // minimum valid epoch
        Serial.println("I Am Time");
        delay(100);
    }
while (time(nullptr) < 1617460172)

This code in the setup gets time from the NTP service. And proceeds further only if the value received is greater than the minimum valid epoch.

I tried the below but it always says the time is 4PM in setup. Once the loop starts the time is correct.

    // ////////////////////
    char buffer[80];
    struct tm* timeinfo;

    timeinfo = localtime(&rawtime);
    strftime(buffer, 80, "%Y%m%d %r",timeinfo);
    Serial.println(buffer);
 
    delay(5000);
    /////////
    timeinfo = localtime(&rawtime);
    strftime(buffer, 80, "%Y%m%d %r",timeinfo);
    Serial.println(buffer);

     // /////////////

    while (time(nullptr) < 1617460172)  { // minimum valid epoch
    
        Serial.println("I Am Time");
        delay(100);

    }

    timeinfo = localtime(&rawtime);
    strftime(buffer, 80, "%Y%m%d %r",timeinfo);
    Serial.println(buffer);

    Serial.println("leaving setup");

The time(nullptr) returns a value which is compared with the epoch to determine if the time received has some relevance to the correct time. This value needs to be assigned to a variable. I dont see that assignment anywhere in the code.

Try making a second call to the time() function after exiting the while loop like:

time(&rawtime);

Then u can continue with displaying time values.

That didn't do it. Still 4PM when exiting setup.

What would I do with the variable I assign time(&rawtime); to? It's comparing the value in the while loop.

This is the output i'm seeing on serial

................Connected
IP Address: 10.5.0.161   
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
I Am Time
19691231 04:00:00 PM
19691231 04:00:00 PM
19691231 04:00:00 PM
leaving setup
47
LED OFF
20211212 03:47:42 PM
47
LED OFF

Getting Date & Time From NTP Server With ESP8266 NodeMCU (lastminuteengineers.com)

Yea, that's a different tangent (library).

The variable rawtime in the time(&rawtime) has the time value obtained from the ntp server. You need to manipulate this value within the setup to set time value before exiting setup.

Someone pointed this to me. It doesn't compile but maybe it has the answer. I'll look at it more tomorrow.

i tried to apply my advice from answer #2 and for me this works like expected:

/*
  NTP TZ DST - bare minimum - wait for first sync
  NetWork Time Protocol - Time Zone - Daylight Saving Time

  Our target for this MINI sketch is:
  - get the SNTP request running
  - set the timezone
  - (implicit) respect daylight saving time
  - how to "read" time to be printed to Serial.Monitor

  This example is a stripped down version of the NTP-TZ-DST (v2) from the ESP8266
  and contains some #precompiler defines to make it working for
  - ESP32 core 1.0.5
  - ESP8266 core 2.7.4

  by noiasca https://werner.rothschopf.net/microcontroller/202103_arduino_esp32_ntp_en.htm
  2021-12-14
*/

//#include <credentials.h>                               // that's just for my unknown credentials ;-)

#ifndef STASSID
#define STASSID "your-ssid"                            // set your SSID
#define STAPSK  "your-password"                        // set your wifi password
#endif

/* Configuration of NTP */
// choose the best fitting NTP server pool for your country
#define MY_NTP_SERVER "at.pool.ntp.org"

// choose your time zone from this list
// https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
#define MY_TZ "CET-1CEST,M3.5.0/02,M10.5.0/03" // Berlin, Vienna, Rom, ...

/* Necessary Includes */
#ifdef ARDUINO_ARCH_ESP32
#include <WiFi.h>                   // we need wifi to get internet access
#endif
#ifdef ARDUINO_ARCH_ESP8266
#include <ESP8266WiFi.h>
#endif
#include <time.h>                   // time() ctime()

/* Globals */
time_t now;                         // this is the epoch
tm tm;                              // the structure tm holds time information in a more convient way

void showTime() {
  time(&now);                       // read the current time
  localtime_r(&now, &tm);           // update the structure tm with the current time
  Serial.print("year:");
  Serial.print(tm.tm_year + 1900);  // years since 1900
  Serial.print("\tmonth:");
  Serial.print(tm.tm_mon + 1);      // January = 0 (!)
  Serial.print("\tday:");
  Serial.print(tm.tm_mday);         // day of month
  Serial.print("\thour:");
  Serial.print(tm.tm_hour);         // hours since midnight  0-23
  Serial.print("\tmin:");
  Serial.print(tm.tm_min);          // minutes after the hour  0-59
  Serial.print("\tsec:");
  Serial.print(tm.tm_sec);          // seconds after the minute  0-61*
  Serial.print("\twday");
  Serial.print(tm.tm_wday);         // days since Sunday 0-6
  if (tm.tm_isdst == 1)             // Daylight Saving Time flag
    Serial.print("\tDST");
  else
    Serial.print("\tstandard");
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  Serial.println("\nNTP TZ DST - bare minimum");

#ifdef ARDUINO_ARCH_ESP32
  // ESP32 seems to be a little more complex:
  configTime(0, 0, MY_NTP_SERVER);   // 0, 0 because we will use TZ in the next line
  setenv("TZ", MY_TZ, 1);             // Set environment variable with your time zone
  tzset();
#else
  // ESP8266
  configTime(MY_TZ, MY_NTP_SERVER); // --> for the ESP8266 you only need this IMPORTANT ONE LINER in your sketch!
#endif

  // start network
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  WiFi.begin(STASSID, STAPSK);
  while (WiFi.status() != WL_CONNECTED) {
    delay(200);
    Serial.print ( "." );
  }
  Serial.println("\nWiFi connected");
  // by default, the NTP will be started after 60 secs

  while (time(nullptr) < 1600000000)  { // wait for the first time sync
    Serial.print("w");
    delay(100);
  }
  Serial.println();
}

void loop() {
  showTime();
  delay(1000); // dirty delay
}

The sketch will remain in setup() unit the first working sync

not only after a reset, also after a complete power down.

21:53:53.081 -> NTP TZ DST - bare minimum
21:53:53.282 -> ..................
21:53:57.448 -> WiFi connected
21:53:57.448 -> www
21:53:57.749 -> year:2021	month:12	day:14	hour:21	min:53	sec:57	wday2	standard
21:53:58.700 -> year:2021	month:12	day:14	hour:21	min:53	sec:58	wday2	standard
21:53:59.704 -> year:2021	month:12	day:14	hour:21	min:53	sec:59	wday2	standard

I'm on ESP core 2.7.4.

@noiasca Thank you for the very clean working example. I'm not sure exactly why yours worked because I did put the loop in setup. I even put it in there twice.

One thing to note is that updating the time slows down the main loop noticeably. I don't need excellent time keeping so I just update the time every few minutes.

Anyway, my cat feeder is almost done. Thanks.