ESP8266 NodeMCU NTP Client-Server: Get Date and Time (Arduino IDE)

In this tutorial you’ll learn how to get date and time from an NTP server using the ESP8266 NodeMCU with Arduino IDE. Getting date and time is useful in data logging projects to timestamp readings. To get time from an NTP Server, the ESP8266 needs to have an Internet connection and you don’t need additional hardware (like an RTC clock).

Before proceeding make sure you have the ESP8266 board installed in Arduino IDE:

Recommended: Get Date and Time with ESP32 NTP Client-Server

NTP (Network Time Protocol)

NTP stands for Network Time Protocol and it is a networking protocol for clock synchronization between computer systems. In other words, it is used to synchronize computer clock times in a network.

There are NTP servers like pool.ntp.org that anyone can use to request time as a client. In this case, the ESP8266 is an NTP Client that requests time from an NTP Server (pool.ntp.org).

Installing the NTPClient Library

We’ll use the NTPClient library to get time. In your Arduino IDE, go to Sketch Library Manage Libraries. The Library Manager should open.

Search for NTPClient and install the library by Fabrice Weinber as shown in the following image.

NTPClient Library Time Functions

The NTPClient Library comes with the following functions to return time:

getDay() – returns an int number that corresponds to the the week day (0 to 6) starting on Sunday;

getHours() – returns an int number with the current hour (0 to 23) in 24 hour format;

getMinutes() – returns an int number with the current minutes (0 to 59);

getSeconds() – returns an int number with the current second;

getEpochTime() – returns an unsigned long with the epoch time (number of seconds that have elapsed since January 1, 1970 (midnight GMT);

getFormattedTime() – returns a String with the time formatted like HH:MM:SS;

his library doesn’t come with functions to return the date, but we’ll show you in the code how to get the date (day, month and year).

ESP8266 NodeMCU Code

The following code connects the ESP8266 to an NTP Server (pool.ntp.org) to request date and time. It displays the current date and time in several formats in the Serial Monitor.

/*
 Welcome to Gnd_to_Vcc!!
*/

#include <ESP8266WiFi.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, "pool.ntp.org");

//Week Days
String weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

//Month names
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  
  // Connect to Wi-Fi
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

// 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(0);
}

void loop() {
  timeClient.update();

  unsigned long epochTime = timeClient.getEpochTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);
  
  String formattedTime = timeClient.getFormattedTime();
  Serial.print("Formatted Time: ");
  Serial.println(formattedTime);  

  int currentHour = timeClient.getHours();
  Serial.print("Hour: ");
  Serial.println(currentHour);  

  int currentMinute = timeClient.getMinutes();
  Serial.print("Minutes: ");
  Serial.println(currentMinute); 
   
  int currentSecond = timeClient.getSeconds();
  Serial.print("Seconds: ");
  Serial.println(currentSecond);  

  String weekDay = weekDays[timeClient.getDay()];
  Serial.print("Week Day: ");
  Serial.println(weekDay);    

  //Get a time structure
  struct tm *ptm = gmtime ((time_t *)&epochTime); 

  int monthDay = ptm->tm_mday;
  Serial.print("Month day: ");
  Serial.println(monthDay);

  int currentMonth = ptm->tm_mon+1;
  Serial.print("Month: ");
  Serial.println(currentMonth);

  String currentMonthName = months[currentMonth-1];
  Serial.print("Month name: ");
  Serial.println(currentMonthName);

  int currentYear = ptm->tm_year+1900;
  Serial.print("Year: ");
  Serial.println(currentYear);

  //Print complete date:
  String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
  Serial.print("Current date: ");
  Serial.println(currentDate);

  Serial.println("");

  delay(2000);
}

Demonstration

After inserting your network credentials and modifying the variables to adjust the time to your timezone, test the example.

Upload the code your ESP8266 board. Make sure you have the right board and COM port selected.

Open the Serial Monitor at a baud rate of 115200. The date and time should be displayed in several formats as shown below.

Conclusion

In this tutorial you’ve learned how to get date and time from an NTP server using the ESP8266. This is specially useful for data logging projects that have access to the internet.

If you don’t have access to the internet, you can use an RTC module like the DS1307.

Published by Gnd_To_Vcc

Here to spread my knowledge . Knowledge should always be spread not stored.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: