Getting Date and Time with ESP32 on Arduino IDE (NTP Client)

In this tutorial we’ll show you how to get date and time using the ESP32 and Arduino IDE. Getting date and time is especially useful in data logging to timestamp your readings. If your ESP32 project has access to the Internet, you can get date and time using Network Time Protocol (NTP) – you don’t need any additional hardware.

Note: there’s an easier and updated guide to get date and time with the ESP32 with the pre-installed time.h library: ESP32 NTP Client-Server: Get Date and Time (Arduino IDE).

Before proceeding with this tutorial you should have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 on the Arduino IDE, if you haven’t already.

NTP Client Library

The easiest way to get date and time from an NTP server is using an NTP Client library. For that we’ll be using the NTP Client library forked by Taranais. Follow the next steps to install this library in your Arduino IDE:

  1. Click here to download the NTP Client library. You should have a .zip folder in your Downloads
  2. Unzip the .zip folder and you should get NTPClient-master folder
  3. Rename your folder from NTPClient-master to NTPClient
  4. Move the NTPClient folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Getting Date and Time from NTP Server

Here we provide a sample code to get date and time from the NTP Server. This example was modified from one of the library examples.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com
  Based on the NTP Client library example
*********/

#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

// Initialize a NTPClient to get time
  timeClient.begin();
  // Set offset time in seconds to adjust for your timezone, for example:
  // GMT +1 = 3600
  // GMT +8 = 28800
  // GMT -1 = -3600
  // GMT 0 = 0
  timeClient.setTimeOffset(3600);
}
void loop() {
  while(!timeClient.update()) {
    timeClient.forceUpdate();
  }
  // The formattedDate comes with the following format:
  // 2018-05-28T16:00:13Z
  // We need to extract date and time
  formattedDate = timeClient.getFormattedDate();
  Serial.println(formattedDate);

  // Extract date
  int splitT = formattedDate.indexOf("T");
  dayStamp = formattedDate.substring(0, splitT);
  Serial.print("DATE: ");
  Serial.println(dayStamp);
  // Extract time
  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
  Serial.print("HOUR: ");
  Serial.println(timeStamp);
  delay(1000);
}

View raw code

To get more NTP examples, in the Arduino IDE, go to File Examples NTPClient.

How the Code Works

Let’s take a quick look at the code to see how it works. First, you include the libraries to connect to Wi-Fi and get time and create an NTP client.

#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

Setting SSID and password

Type your network credentials in the following variables, so that the ESP32 is able to establish an Internet connection and get date and time from the NTP server.

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Preparing NTP Client

The following two lines define an NTP Client to request date and time from an NTP server.

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

Then, initialize String variables to save the date and time.

String formattedDate;
String dayStamp;
String timeStamp;

In the setup() you initialize the Serial communication at baud rate 115200 to print the results:

Serial.begin(115200);

These next lines connect the ESP32 to your router.

// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Next, initialize the NTP client to get date and time from an NTP server.

timeClient.begin();

You can use the setTimeOffset() method to adjust the time for your timezone in seconds.

timeClient.setTimeOffset(3600);

Here are some examples for different timezones:

  • GMT +1 = 3600
  • GMT +8 = 28800
  • GMT -1 = -3600
  • GMT 0 = 0

These next lines ensure that we get a valid date and time:

while(!timeClient.update()) {
  timeClient.forceUpdate();
}

Note: sometimes the NTP Client retrieves 1970. To ensure that doesn’t happen we need to force the update.

Getting date and time

Then, convert the date and time to a readable format with the getFormattedDate() method:

formattedDate = timeClient.getFormattedDate();

The date and time are returned in the following format:

2018-04-30T16:00:13Z

If you want to get date and time separately, you need to split that string. The “T” letter separates the date from the time, so we can easily split that String. That’s what we do in these next lines.

// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
Serial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
Serial.println(timeStamp);

The date is saved on the dayStamp variable, and the time on the timeStamp variable.The time is requested and printed in every second.

Testing the Code

Upload the code to the ESP32. Make sure you have the right board and COM port selected. After uploading the code, press the ESP32 “Enable” button, and you should get the date and time every second as shown in the following figure.

Wrapping Up

In this tutorial we’ve shown you how to easily get date and time with the ESP32 on the Arduino IDE using an NTP server. The code provided is not useful by itself. The idea is to use the example provided in this guide in your own projects to timestamp your sensor readings.

This method only works if the ESP32 is connected to the Internet. If your project doesn’t have access to the internet, you need to use other method. You can use an RTC module like the DS1307.

We have other tutorials related with ESP32 that you may also like:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

84 thoughts on “Getting Date and Time with ESP32 on Arduino IDE (NTP Client)”

  1. Thanks for this and all of your tutorials, they are great and easy to follow. You provide a great service for all of us hobbyist that love to make projects with the Arduino but don’t have a lot of programming skills. Again thanks.

    Reply
  2. Hi Ruis, thanks for explaining.
    But I get a compilation error:
    /home/hans/Arduino/CV_temperatuurmeter__NTPClient/CV_temperatuurmeter__NTPClient.ino: In function ‘void loop()’:
    CV_temperatuurmeter__NTPClient:96: error: ‘class NTPClient’ has no member named ‘getFormattedDate’
    formattedDate = timeClient.getFormattedDate();

    Can you tell me whatÅ› going wrong ? Because getFormattedDate() is mentioned within the library

    Reply
        • Don’t know if you’re still having an issue, gaga, but I found this.
          github.com/arduino-libraries/NTPClient/issues/36

          and found that while the getFormattedDate() is in the .h file, it was absent from the .cpp. I ended up using their additions and adding this to NTPClient.cpp

          String NTPClient::getFullFormattedTime() {
          time_t rawtime = this->getEpochTime();
          struct tm * ti;
          ti = localtime (&rawtime);

          uint16_t year = ti->tm_year + 1900;
          String yearStr = String(year);

          uint8_t month = ti->tm_mon + 1;
          String monthStr = month tm_mday;
          String dayStr = day tm_hour;
          String hoursStr = hours tm_min;
          String minuteStr = minutes tm_sec;
          String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);

          return yearStr + "-" + monthStr + "-" + dayStr;

          and this to NTPClient.h

          String getFullFormattedTime();

          int getYear();
          int getMonth();
          int getDate();

          Hopefully that helps!

          Reply
          • Hi Marshall.
            Thank you for sharing your solution.
            I’ll have to take a look through this.
            Regards,
            Sara

          • Your solution doesn’t address the issue mentioned, that is getFormattedDate() does not exist. I copied your code into the cpp file and still get the same compilation error.

          • Hi.
            Make sure you use the NTP Client library we mention in the tutorial and follow the suggested installation method.
            Regards,
            Sara

  3. But what if the Internet connection goes down? The solutioncould be using TimeLib library as backup.
    And NTP server to update TimeLib from time to time.
    I did that for ESP8266 but for ESP32 I had no success.
    Thanks, Rui!

    Reply
  4. I get the date and time from my router using
    client.print(“GET / HTTP/1.1\r\n Host: 192.168.1.254 \r\nConnection: close\r\n\r\n’ | nc 192.168.1.254 80” );
    which returns the local time.

    Reply
  5. It would great to go one step further, by writing the time to ds3132/ds1307 and reading from ds3132/ds1307 every 6 hours.

    Reply
    • Hi.
      Yes, that is a great idea. We intend to make a tutorial on how to use the DS1307 RTC with the ESP32.
      Regards,
      Sara 🙂

      Reply
    • Hi Anthony.
      We’re using the NTP library forked by Taranais.
      Here is the github page: github.com/taranais/NTPClient
      I hope this helps.
      Regards,
      Sara 🙂

      Reply
  6. Hi, I really appreaciate that you provided all that information for us. Thanks!

    I am currently working on a project and I need to timestamp some sensor readings, as you exemplified. I’m not quite sure on how to do that, though. Any help would be awesome!!! Could you give me some tips?

    Thanks again.

    Reply
  7. Cannot declare variable ‘ntpUDP’ to be of abstract type ‘WiFiUDP’
    Line 10.

    The problem came when compiling for esp8266, Wemos D1mini. Anyone having the same problem or anyone who know how to fix this

    Reply
  8. all in all it shows how sick this is: esp8266 provides hundreds of working examples for getting the time from an ntp server out there.

    For esp32 you’ll find as many examples that DON’T do. If we can’t

    Please don’t get me wrong: I really approciate your help but if the foundation is wrong with both, esp’s as well as the i-net itself, it won’t solve the general issue.

    Reply
  9. Hello,

    First of all, thank you very much for the article! It’s really nice.

    I realised this method doesn’t take in count summer time change, so it is necessary to change the time manually twice every year.

    Is there any example or server to get the time from, and which takes into account this summer time change?

    Thank you very much in advance,

    Xabi

    Reply
    • Hi.
      This doesn’t take into account summer time change.
      In the following link, people suggest that you verify the date and make the changes accordingly: github.com/arduino-libraries/NTPClient/issues/40
      I hope this helps.
      Regards,
      Sara

      Reply
  10. Hey.

    How can I change the date display from (Y-M-D) 2019-10-6 to 6-10-2019 ( D-M-Y). Because that is the European way of representation.
    Thank you for your beautiful and educational work.
    Greetings from Bert in the Netherlands.

    Reply
    • Hi Bert.
      The method we use here gets the date in that format.
      You may cut the string to save the month, year and day on different variables and then concatenate the variables in your desired order.
      Regards,
      Greetings from Portugal 😀

      Reply
  11. Yes i now, but don’t know how to do that, I didn’t succeed, sorry. Can you explain briefly how to do it?

    I was in Tavira 12 years ago, too hot !! haha

    Winter now here.

    Reply
  12. I can not get the date for this program. If I change the command “getFormattedDate” for getFormattedTime” works fine but it does not give me the date. I changed the library NTPClient for the one suggested here. However it does not work. To see if the problem was the IDE , I re installed the last version in a very a neat way removing upto arduino15 files. Howver, the problem continues. I would be very thankfull if you give me any clue to solve the problem. I add the compilation print out.

    Sincerely yours

    washington

    Arduino:1.8.12 (Windows 10), Tarjeta:”ESP32 Wrover Module, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), QIO, 80MHz, 921600, None”

    C:\Users\washington\MIS_ARDUINO_FILES\PROYECTO_RIEGO_AUTOM\ESP32_WEB_SD\ESP32_WEB_SD.ino: In function ‘void getTimeStamp()’:

    ESP32_WEB_SD:161:30: error: ‘class NTPClient’ has no member named ‘getFormattedDate’

    formattedDate = timeClient.getFormattedDate();
    Se encontraron varias bibliotecas para “SD.h”
    Usado: C:\Users\washington\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\SD
    No usado: C:\Program Files (x86)\Arduino\libraries\SD
    Se encontraron varias bibliotecas para “WiFi.h”
    Usado: C:\Users\washington\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFi
    No usado: C:\Program Files (x86)\Arduino\libraries\WiFi
    exit status 1
    ‘class NTPClient’ has no member named ‘getFormattedDate’

    Reply
      • I also have the same issue. the sketch keep showing error when i use getFormattedDate. Then i change to getFormattedTime, but i can’t get the date, only time available. Do you have any idea what’s going on?

        Regards

        Reply
  13. The code below was tested on an ESP01 (black).
    There is a very easy way to get a tm structure using and NTP server:

    #include
    #include
    #include "time.h"

    NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);
    unsigned long nowLong;
    struct tm * ptm;

    vois setup() {
    timeClient.begin();
    }

    void loop() {
    timeClient.update();
    nowLong = timeClient.getEpochTime();
    ptm = gmtime ((time_t *)&nowLong);
    Serial.printf("monthday=%d, month=%d,wdayno=%d, hour=%d, minute=%d, second=%d\r\n",
    ptm->tm_mday,
    ptm->tm_mon,
    ptm->tm_wday,
    ptm->tm_hour,
    ptm->tm_min,
    ptm->tm_sec
    );

    }

    Reply
    • The code can be further improved by loading the retrieved(from NTP) into the local inbuilt RTC of the 8266 with the following code, but it is recommended to update from internet at least daily as the inbuilt RTC is not dead accurate(Depends on application). Furthermore, it seems to take about 30 secs for the update of the inbuilt RTC to take effect, which is why the print is not done until the year changes from the default 70.

      The code to set the local RTC:

      unsigned long nowLong;
      timeval tv;

      timeClient.update();
      nowLong = timeClient.getEpochTime();
      tv.tv_sec=nowLong;
      tv.tv_usec = 0;
      settimeofday(&tv, 0);

      The code to retrieve from local RTC:

      struct tm * ptm;
      nowLong = time(nullptr);
      ptm = gmtime ((time_t *)&nowLong);
      //only printf after time has been initialised
      if (ptm->tm_year != 70) {
      Serial.printf("monthday=%d, month=%d,wdayno=%d, hour=%d, minute=%d, second=%d, year=%d\r\n",
      ptm->tm_mday,
      ptm->tm_mon,
      ptm->tm_wday,
      ptm->tm_hour,
      ptm->tm_min,
      ptm->tm_sec,
      ptm->tm_year + 1900
      );

      Reply
  14. Thank you. That lifted a bit of the fog for me, trying to use NTP for the first time.

    BTW, you have a typo: Time offset is seconds, not mS 🙂

    Reply
  15. I appreciate your tutorial very much. It is very helpful. I have a question about extracting the timestamp with milliseconds as a unit, since I would like to measure acceleration using ESP32 and a sensor. What I was able to find as to this issue were examples limited to seconds as a unit. I appreciate very much if you would give a advice or references I should see.

    Best Regards,
    S.K. from Japan

    Reply
  16. Hello Rui and Sara; first, thanks for the tutorial.
    I have a similar clock sketch that uses NTP Client to show Hours, Minutes and Seconds and also Year, Month and Day but since I live in Brazil the sequence would be Day, Month and Year so I would like your help to change this sequence, therefore, part of the code below:

    void Date_time_weather_Display()
    {
    formattedDate = timeClient.getFormattedDate();
    //Ano, Mês e Dia
    //Serial.println(formattedDate);
    int splitT = formattedDate.indexOf(“T”);
    int N_year = formattedDate.indexOf(“-“);
    String N_year1 = formattedDate.substring(0, N_year);
    String N_month = formattedDate.substring(5, 7);
    String N_day = formattedDate.substring(8, 10);
    tft.setTextColor(TFT_MAGENTA, TFT_BLACK);
    tft.setTextSize(2);
    tft.setCursor( 20, 20 );
    tft.println(N_year1);
    tft.drawBitmap(74, 20, title[18], 16, 16, TFT_WHITE); //ano
    tft.setCursor( 106, 20 );
    tft.println(N_month);
    tft.drawBitmap(138, 20, title[17], 16, 16, TFT_WHITE); //mês
    tft.setCursor( 170, 20 );
    tft.println(N_day);
    tft.drawBitmap(202, 20, title[10], 16, 16, TFT_WHITE); //dia
    //Dia da Semana
    tft.drawBitmap(234, 20, title[14], 16, 16, TFT_WHITE); //Estrela
    tft.drawBitmap(250, 20, title[11], 16, 16, TFT_WHITE); //期
    if (Week_check != timeClient.getDay())
    {
    tft.fillRect(266, 10, 16, 16, TFT_BLACK);
    Week_check = timeClient.getDay();
    }
    tft.drawBitmap(282, 20, title[timeClient.getDay()], 16, 16, TFT_MAGENTA);

    //Hora agora
    timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() – 1);
    tft.setTextColor(TFT_YELLOW, TFT_BLACK);
    tft.setTextSize(6);
    tft.setCursor( 15, 180 );
    tft.println(timeStamp);
    }

    Thanks and Greetings from Brazil

    Reply
  17. When I compile the code I’m getting the following error message.
    I’m using the using the NTP Client library forked by Taranais.
    Please advise, thank you, Martin

    Arduino: 1.8.19 (Linux), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    ‘class NTPClient’ has no member named ‘getFormattedDate’; did you mean ‘getFormattedTime’?
    159 | Serial.println(timeClient.getFormattedDate());
    | ^~~~~~~~~~~~~~~~
    | getFormattedTime
    ‘class NTPClient’ has no member named ‘getFormattedDate’; did you mean ‘getFormattedTime’?

    Reply
    • Hi.
      It seems that the getFormattedDate method is outdated.
      Now, you should use getFormattedTime. I need to review and update this post.
      Thanks for your comment.
      Regards,
      Sara

      Reply
  18. I used NTPClient on my ESP32 for over a year. It was on a monitor that ran 24/7. The time code ran once a day. It worked great until it didn’t. About the beginning of April 2022 it just quit working. It would just time out (maximum of 20 tries in the loop). This happened both on the remote unit and at home on a different ESP32 and different WiFi. I posted the issue on https://github.com/arduino-libraries/NTPClient/issues/172 but no comments. I gave up and now retrieve what I want from a webpage using the powerful php time functions so I am happy but also curious about what is going on.

    By the way, I never would have gotten my project running without the excellent tutorials on this site. Thank you for that. The only suggestion I would have is always put a counter in your while loops so they are guaranteed to exit.

    Reply
  19. Hello,
    I tried this code but with Ethernet module ENC28J60 using EthernetENC Library.
    It’s just shows 1970-1-1 and time 00:00:00.

    also tried configtime, but ithink config time will work with wifi only

    Reply
  20. I have an ESP8266 system running a Finate Sate Machine and depending on the hour of the day it will perform different routines. However, I have only been able to compare values using the Hour timeClient.getHours(). How can I check if time is say 21:30hrs? Can I somehow add timeClient.getHours() with timeClient.getMinutes()?

    Reply
  21. I have got this error. What can I do?
    That mean’s “getFormattedDate” is no member named in class NTPClient..

    G:\키재기\Arduino Nodemcu v2\Naver Blog\NodeMCU Get Real Time\NodeMCU Get Real Time.ino: In function ‘void loop()’:
    G:\키재기\Arduino Nodemcu v2\Naver Blog\NodeMCU Get Real Time\NodeMCU Get Real Time.ino:95:28: error: ‘class NTPClient’ has no member named ‘getFormattedDate’; did you mean ‘getFormattedTime’?

    exit status 1

    Compilation error: ‘class NTPClient’ has no member named ‘getFormattedDate’; did you mean ‘getFormattedTime’?

    Reply
    • Hi.
      You probably installed the wrong library.
      Please install the library shown in the tutorial using the method we describe.
      Regards,
      Sara

      Reply
  22. Thank you for your help to any project . You are top in this field.
    I would like to ask a specific question. If a have a device , based on esp32, and upload the code of the current page what going on if the time change to the summer time ? The NTP server will continue to give me the winter time(wrong time) or will automaticly change to the summer time. Do i need change something in the code? Thank you very much for your help

    Reply
  23. Hello good day,

    First of all:
    I have read several of your tutorials and find them all quite excellent, especially the very good explanation of how each code section is explained. Big compliments!!!

    I use the above code as a function in several different sketches and it always works everywhere until today.

    As of today, I am getting the following error message in a single sketch when compiling; all other sketches continue to work fine.

    c:/users/manfr/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../xtensa-esp32-elf/bin/ld.exe: C:\Users/manfr\AppData\Local\Temp\arduino\sketches\46F94ADC69DD0F0DD6FDE98911FFD337\sketch\time_acquisition_temp_read-store.ino.cpp.o:(.literal._Z10Date_Timev+0x2c): undefined reference to NTPClient::getFormattedDate(unsigned long)'
    c:/users/manfr/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../xtensa-esp32-elf/bin/ld.exe: C:\Users\manfr\AppData\Local\Temp\arduino\sketches\46F94ADC69DD0F0DD6FDE98911FFD337\sketch\time_acquisition_temp_read-store.ino.cpp.o: in function
    date_time()’:
    C:\Users\manfr\Documents\Arduino\time_acquisition_temp_read_stores/time_acquisition_temp_read_stores.ino:218: undefined reference to `NTPClient::getFormattedDate(unsigned long)’
    collect2.exe: error: ld returned 1 exit status

    exit status 1

    The call and the code are absolutely the same in all sketches. In all of them the variable ‘formattedDate’ is declared in the preprocessing as follows:
    // Variables to save date and time
    String formattedDate;
    String dayStamp;
    String timeStamp;

    Can you help me to find and fix my error?

    Thank you in advance for your efforts

    Manfred Prefi

    translated from German with DeepL

    Reply
      • Hi,
        Yes, also I got once at the error message when compiling the suggestion to enter getFormattedTime(…) instead of getFormattedDate(..), but that didn’t work, I got only the time (without date).
        My new sketch works now – see my reply to Sara Santos.
        Thanks for the answer.
        Manfred

        Reply
      • All libraries were installed correctly, and the code for time reading in a separate sketch worked fine too.
        I have now re-edited my entire sketch and it works fine now.
        I don’t know what error was in the original code, maybe a missing statement.
        Thanks for the help and best regards to Porto.
        Manfred

        Reply
          • Hallo,

            I have again the same problem with the above mentioned scetch, which worked fine until now, that I just wanted to flash to another boaed.

            With the following statement comes an error when compiling:

            formattedDate = timeClient.getFormattedDate();

            The error message is:

            Compilation error: ‘class NTPClient’ has no member named ‘getFormattedDate’; did you mean ‘getFormattedTime’?

            I compared again with your code and could not find any discrepancy.
            I am working with the same machine and the same libraries.

            What could be the reason for this?
            Thanks for your help

  24. There’s no need for any additional library, simply load “time.h” like this


    //Ok, a quick and brief tutorial upon NTP with Arduino:

    //First, in the global section, have

    #include "time.h" // we'll need that later on

    char Result[8]; // placeholder, string for what we request from NTP

    // We use the old "uint" declaration mostly for heritage

    uint32_t targetTime = 0; // Universal Counter

    uint8_t hh, mm, ss; // We want hours, minutes and seconds in the first place, expand to your demands

    // Definitions for the latter to use "configTime" function of "time.h"

    const char* ntpServer = "192.168.178.1"; // local NTP-Server in my case, here inside LAN; use any of "pool.ntp.org" a. s. o.
    const long gmtOffset_sec = 3600; // CET vs. UTC
    const int daylightOffset_sec = 0; // Fiddle around with tzData()

    // Core function: "Void()" for being in the global scope

    void syncNTP() {
    struct tm timeinfo;

    // "timeinfo" now is of the strucrure "tm"
    // filled with getLocalTime() will provide us with more than we expect

    if(!getLocalTime(&timeinfo)){
    return; // we don't care: Success on success, fail on fail; next try only 60 min away
    }
    hh = timeinfo.tm_hour;
    mm = timeinfo.tm_min;
    ss = timeinfo.tm_sec;
    }

    void setup(void) {

    WiFi.mode(WIFI_STA); //connect WiFi
    WiFi.begin(ssid, password);

    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); // Here, our NTP-client role starts off!

    targetTime = millis() + 1000;
    syncNTP();

    }

    void loop() {
    if (targetTime < millis()) {
    targetTime += 1000;
    ss++; // Advance second
    if (ss==60) {
    ss=0;
    mm++; // Advance minute
    if(mm>59) {
    mm=0;
    hh++; // Advance hour
    if (hh>23) {
    hh=0;
    }
    syncNTP(); // NTP-update hourly, edit for own needs
    }
    }

    sprintf(Result, "%02d:%02d:%02d", hh, mm, ss);
    // From here, print/use $Result wherever you want?

    }
    }

    Reply
      • Hi, Sara,

        thank you for answering.

        My main point in my comment was that, in the named example code, the main focus is on the representation of the members of “&timeinfo” as char().

        For use with MCUs, it is far more common to get the values as numeric int. Although that’s pretty trivial, the tutorial shows how to print the NTP-result as a formatted string, but not how to easily get the values as ints to process them. So if you’re not too familiar with the tm structure, this may seem a bit, say, “complicated”.

        Hence the comment.

        Thanks again, have nice holidays!

        Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.