Reading NTP Client Server to get current Date and Time with ESP32

Last Updated on May 13, 2024

We can get Real Time and Date from Internet by using ESP32 board and it can be used in several ways to enhance our projects additionally it is suitable for IoT and Real time based applications. In this tutorial you can lear about basic things to read time and date from internet and printing it in Arduino Serial Monitor. To get the Time from NTP (Network Time Protocol) server we need Internet Connection through Wi-Fi and ESP32 Board.

If you are new to ESP32 then read about Getting Started with ESP32 with Arduino IDE.

What is NTP?

It is a networking protocol used to synchronize the clocks of computers and other devices on a network (Internet). NTP allows devices to maintain accurate timekeeping by synchronizing their clocks with reference time sources called NTP servers. NTP uses Client Server architecture and have one or more primary time servers connected with Atomic Clock or GPS satellites as source time date source and then provide time synchronization services to client devices on the network.

Circuit Diagram

Just Connect ESP32 Board with Computer.

Construction & Working

Connecting ESP32 with Computer through data Cable and providing exact Wi-Fi name and Password in Arduino code is enough to get Current Time and Date.

To read Time and Date from NTP server we can use the following urls “pool.ntp.org” and “time.nist.gov” and these domains provides real time clock information on request.

ESP32 Arduino Code to get Time and Date

/* Code edited by theorycircuit Digital Team */
#include <WiFi.h>
#include "time.h"
#include "sntp.h"

const char* ssid       = "YOUR_SSID"; /* Put your Wi-Fi Name */
const char* password   = "YOUR_PASSWORD"; /* Put your Wi-Fi Password */

const char* ntpServer1 = "pool.ntp.org";
const char* ntpServer2 = "time.nist.gov";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

const char* time_zone = "CET-1CEST,M3.5.0,M10.5.0/3";  // TimeZone rule for Europe/Rome including daylight adjustment rules (optional)

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

// Callback function (get's called when time adjusts via NTP)
void timeavailable(struct timeval *t)
{
  Serial.println("Got time adjustment from NTP!");
  printLocalTime();
}

void setup()
{
  Serial.begin(115200);

  // set notification call-back function
  sntp_set_time_sync_notification_cb( timeavailable );

  /**
   * NTP server address could be aquired via DHCP,
   *
   * NOTE: This call should be made BEFORE esp32 aquires IP address via DHCP,
   * otherwise SNTP option 42 would be rejected by default.
   * NOTE: configTime() function call if made AFTER DHCP-client run
   * will OVERRIDE aquired NTP server address
   */
  sntp_servermode_dhcp(1);    // (optional)

  /**
   * This will set configured ntp servers and constant TimeZone/daylightOffset
   * should be OK if your time zone does not need to adjust daylightOffset twice a year,
   * in such a case time adjustment won't be handled automagicaly.
   */
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);

  /**
   * A more convenient approach to handle TimeZones with daylightOffset 
   * would be to specify a environmnet variable with TimeZone definition including daylight adjustmnet rules.
   * A list of rules for your zone could be obtained from https://github.com/esp8266/Arduino/blob/master/cores/esp8266/TZ.h
   */
  //configTzTime(time_zone, ntpServer1, ntpServer2);

  //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");

}

void loop()
{
  delay(5000);
  printLocalTime();     // it will take some time to sync time :)
}

Serial Monitor output

ESP32 Arduino Code to get different Zone Time and Date

/* Code by theorycircuit Digital Team */
#include <WiFi.h>
#include "time.h"
#include "sntp.h"

const char* ssid       = "Your_SSID"; // Put your Wi-Fi Name
const char* password   = "Your_Password"; // Put your Wi-Fi Password

const char* ntpServer1 = "0.us.pool.ntp.org"; // NTP server for New York
const char* ntpServer2 = "0.europe.pool.ntp.org"; // NTP server for London
const char* ntpServer3 = "0.asia.pool.ntp.org"; // NTP server for Dubai and Tokyo

const long  gmtOffsetNY_sec = -5 * 3600; // GMT offset for New York (EST/EDT) is -5 hours
const long  gmtOffsetLondon_sec = 0; // GMT offset for London (GMT/BST) is 0 hours
const long  gmtOffsetDubai_sec = 4 * 3600; // GMT offset for Dubai (GST) is +4 hours
const long  gmtOffsetTokyo_sec = 9 * 3600; // GMT offset for Tokyo (JST) is +9 hours

const int   daylightOffset_sec = 3600; // Daylight saving time offset

void printLocalTime(const char* location, long gmtOffset)
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    return;
  }
  
  // Adjust time for the specified location
  time_t adjustedTime = mktime(&timeinfo) + gmtOffset;
  struct tm *adjustedTimeinfo = localtime(&adjustedTime);
  
  Serial.print(location);
  Serial.print(" Time: ");
  Serial.println(asctime(adjustedTimeinfo));
}

// Callback function (called when time adjusts via NTP)
void timeavailable(struct timeval *t)
{
  Serial.println("Got time adjustment from NTP!");
  printLocalTime("New York", gmtOffsetNY_sec);
  printLocalTime("London", gmtOffsetLondon_sec);
  printLocalTime("Dubai", gmtOffsetDubai_sec);
  printLocalTime("Tokyo", gmtOffsetTokyo_sec);
}

void setup()
{
  Serial.begin(115200);

  // Set notification callback function
  sntp_set_time_sync_notification_cb(timeavailable);

  // Enable DHCP mode for NTP server address acquisition
  sntp_servermode_dhcp(1);

  // Configure NTP servers and time zones
  configTime(gmtOffsetNY_sec, daylightOffset_sec, ntpServer1, ntpServer2);
  configTime(gmtOffsetDubai_sec, daylightOffset_sec, ntpServer3, NULL); // Dubai and Tokyo share the same NTP server

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" CONNECTED");
}

void loop()
{
  delay(5000);
  printLocalTime("New York", gmtOffsetNY_sec);
  printLocalTime("London", gmtOffsetLondon_sec);
  printLocalTime("Dubai", gmtOffsetDubai_sec);
  printLocalTime("Tokyo", gmtOffsetTokyo_sec);
}

Serial Monitor Output




Leave a Reply

Your email address will not be published. Required fields are marked *