Get Epoch/Unix Time with the ESP8266 NodeMCU (Arduino)

This quick guide shows how to get epoch/unix time using the ESP826 NodeMCU board with Arduino IDE. Getting the epoch time can be useful to timestamp your readings, give unique names to files, and other applications. We’ll request the current epoch time from an NTP server, so the ESP8266 board needs to have an Internet connection.

Get Epoch Unix Time with the ESP8266 NodeMCU Arduino

If you want to get date and time in a human readable format, we recommend the following tutorial instead:

What is epoch time?

The Epoch Time (also know as Unix epoch, Unix time, POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).

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.

ESP8266 NodeMCU NTP Network Time Protocol Server Client How it Works

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

ESP8266 Get Epoch/Unix Time Function

To get epoch/unix time with the ESP8266, you can use the following function getTime():

// Function that gets current epoch time
unsigned long getTime() {
  timeClient.update();
  unsigned long now = timeClient.getEpochTime();
  return now;
}

This function returns the current epoch time. Continue reading for a complete example.

ESP8266 NodeMCU Get Epoch/Unix Time Example

Copy the following code to your Arduino IDE. This code connects to the internet and requests the time from an NTP server (pool.ntp.org).

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/epoch-unix-time-esp8266-nodemcu-arduino/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

// Variable to save current epoch time
unsigned long epochTime; 

// Function that gets current epoch time
unsigned long getTime() {
  timeClient.update();
  unsigned long now = timeClient.getEpochTime();
  return now;
}

// Initialize WiFi
void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  timeClient.begin();
}

void loop() {
  epochTime = getTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);
  delay(1000);
}

View raw code

Insert your network credentials in the following variables and the code will work straight away:

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

How the Code Works

Let’s take a quick look on how the code works.

Libraries

First, include the necessary libraries

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

Network Credentials

Insert your network credentials in the following variables so that the ESP8266 can connect to your network.

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

NTP Server

Define an NTP client to get time.

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");

We’ll request the time from pool.ntp.org, which is a cluster of time servers that anyone can use to request the time.

getTime() function

The getTime() function gets and returns the current epoch time.

// Function that gets current epoch time
unsigned long getTime() {
  timeClient.update();
  unsigned long now = timeClient.getEpochTime();
  return now;
}

initWiFi()

The initWiFi() function initializes Wi-Fi and connects the ESP8266 to your local network.

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

setup()

In the setup(), initialize the Serial Monitor at a baud rate of 115200.

Serial.begin(115200);

Call the initWiFi() function to initialize Wi-Fi:

initWiFi();

Initialize the NTP client.

timeClient.begin();

loop()

In the loop(), get the epoch time and save it in the epochTime variable:

epochTime = getTime();

Finally, print the epoch time every second:

Serial.print("Epoch Time: ");
Serial.println(epochTime);
delay(1000);

Demonstration

Upload the code to your ESP8266 board. Then, open the Serial Monitor at a baud rate of 115200. It should connect to Wi-Fi and start printing the current epoch/unix time every second.

ESP8266 NodeMCU Get Epoch Unix Time Serial Monitor

Wrapping Up

This was a quick guide showing you how to get epoch or also known as unix time with the ESP8266 NodeMCU. The epoch time is the number of seconds elapsed since January 1 1970. To get time, we need to connect to an NTP server, so the ESP8266 needs to have access to the internet.

If you’re interested in getting date and time in a human readable format, refer to the next tutorial:

We hope you’ve found this tutorial useful. If you want to learn more about the ESP8266, check our resources:

Thanks for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

7 thoughts on “Get Epoch/Unix Time with the ESP8266 NodeMCU (Arduino)”

  1. Hi Sara and Rui,

    epoc-time does contain all the information so that it is possible to calculate
    the actual date and time.
    Therefore I discovered a pretty small demo-code written by Werner Rotschopf
    https://werner.rothschopf.net/201802_arduino_esp8266_ntp.htm

    It uses the time.h-library and another structure that makes it easier to access day. month, year, hour and a number of day of week etc.

    it inkludes cofiguration of the timezome through a define

    and as an additional hint:
    if you want to use a if-condition like switch something on from 7:54 to 21:19
    caclulating minute of day makes life easier

    actualTime = hour * 60 + minute

    SwitchOnTime = 7 * 60 + 54 = 474
    SwitchOFFTime = 21*60 + 19 = 1279

    so a otherwise complicated if-condition about hours and minutes boils down to

    if (actualTime > SwitchOnTime && actualTime < SwitchOFFTime) {
    //take action;
    }

    best regards Stefan

    Reply
  2. Hi Sara & Rui,
    Thank you for your tutorials.
    I tried the code on a wemos d1 mini. It did not work. It worked when I replaced timeClient.update() by :
    while(!timeClient.update()) {
    timeClient.forceUpdate();
    }
    BR
    Said

    Reply
  3. Stefan,I do that too. But I use the time server to set the internal clock of the esp. Like this
    In declarations:
    #include <SNTPtime.h>
    SNTPtime NTPch(“nl.pool.ntp.org”);
    strDateTime dateTime;
    //for timeserver
    byte actualHour;
    byte actualMinute;
    byte actualsecond;
    int actualyear;
    byte actualMonth;
    byte actualday;
    byte actualdayofWeek;
    //int dayofyear;
    int d;
    uint16_t actualdayofYear;//actualdayofYear
    const uint8_t daysInMonth [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    String maandNaam [] ={“Jan”, “Feb”, “Mrt”, “Apr”, “Mei”, “Juni”, “Juli”,”Aug”,”Sep”,”Okt”,”Nov”,”Dec”};

    In Setup()
    NTPch.setSNTPtime()

    in loop()
    //dateTime = NTPch.getNTPtime(1.0, 1); //from NTP server use this if you want ESP to continuously fetch new time
    dateTime = NTPch.getTime(1.0, 1); // get time from internal clock
    if (dateTime.valid) {
    //NTPch.printDateTime(dateTime);
    actualHour = dateTime.hour;
    actualMinute = dateTime.minute;
    actualsecond = dateTime.second;
    actualyear = dateTime.year;
    actualMonth = dateTime.month;
    actualday = dateTime.day;
    actualdayofWeek = dateTime.dayofWeek;
    }

    Reply
  4. Forgot one thing: I use this function to calculte the ‘day of year’

    int doy()
    {
    d=actualday;//actualday
    //Serial.print(d);
    for (int i=0;i<actualMonth-1;i++){
    d=d+daysInMonth[i];
    //Serial.println(d);
    }
    if (actualMonth > 2 && actualyear %4==0 && actualyear %100 !=0)
    {d=d+1;}
    return d;
    }

    That can come in handy if you want to start or and an action on a specific date. No need to check on day and month but just on say ‘day 200’

    Reply
    • if (actualMonth > 2 && actualyear %4==0 && actualyear %100 !=0)
      {d=d+1;}
      return d;

      To complete it, it should be :
      if (actualMonth > 2 && ((actualyear %4==0 && actualyear %100 !=0) || (actualyear %400==0)))
      {d=d+1;}
      return d;

      Reply
  5. When I implemented ntp updates in my esp8266 projects about two years ago, I realized that dns resolve to the time servers sometimes takes a good amount of time.
    So I got the IP-address on the first call and used it directly on subsequent calls. That made a huge difference.

    Unfortunately most of the time servers seem to be available only temporarily and the IP address becomes invalid from time to time and I had to implement a mechanism that detects that and then requests a new address.

    Another issue is that requests tend to fail quite often, probably due to high trafic. You might have realized that on Your windows pc, when You try to manually force an update of the time by a time server. Sometimes You have to click several time or change to a different server until it reports success.

    I then, more or less accidentally, realized that my router – typically the gateway address – also provides ntp services by default. Since that day I am updating my time with that “server”. It’s blazing fast, almost a 100% reliable and more than good enough for all my projects.

    I use the “time” – lib by Paul Stoffregen(https://github.com/PaulStoffregen/Time) together with my ntp implementation. This makes handling with time data very easy and takes care of regular ntp updates.

    Hope this is of help to anyone.

    Regards

    Frank

    Reply

Leave a Reply to Stefan Ludwig Cancel reply

Download our Free eBooks and Resources

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