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.

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 view 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.

This is our complete guide to program the ESP32 with Arduino IDE, including projects, tips, and tricks!  SIGN UP NOW »

This is our complete guide to program the ESP32 with Arduino IDE, including projects, tips, and tricks! SIGN UP NOW »

#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 baudrate 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 milliseconds.

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:

Download our Free eBooks and Resources

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 program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

22 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.

  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

        • 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!

          • Hi Marshall.
            Thank you for sharing your solution.
            I’ll have to take a look through this.
            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!

  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.

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

    • 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 🙂

    • 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 🙂

  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.

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.