Get Epoch/Unix Time with the ESP32 (Arduino)

This quick guide shows how to get epoch/unix time using the ESP32 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 ESP32 needs to have an Internet connection.

Get Epoch Unix Time with the ESP32 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.

ESP32 NTP Network Time Protocol Server 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 ESP32 is an NTP Client that requests time from an NTP Server (pool.ntp.org).

ESP32 Get Epoch/Unix Time Function

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

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

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

ESP32 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-esp32-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 <WiFi.h>
#include "time.h"

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

// NTP server to request epoch time
const char* ntpServer = "pool.ntp.org";

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

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  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();
  configTime(0, 0, ntpServer);
}

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, you need to include the WiFi library to connect the ESP32 to your local network; and the time library to handle time structures.

#include <WiFi.h>
#include "time.h"

Network Credentials

Insert your network credentials in the following variables so that the ESP32 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

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

const char* ntpServer = "pool.ntp.org";

getTime() function

The getTime() function gets and returns the current epoch time. If it is not able to get the time, it returns 0.

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

initWiFi()

The initWiFi() function initializes Wi-Fi and connects the ESP32 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();

Configure the time using the configTime() function. The first and second arguments correspond to the GMT time offset and daylight saving time. However, because we’re interested in getting epoch time, these arguments should be 0. The last argument is the NTP server (ntpServer):

configTime(0, 0, ntpServer);

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 ESP32 board. Then, open the Serial Monitor at a baud rate of 115200. Press the ESP32 on-board RST button. It should connect to Wi-Fi and start printing the current epoch/unix time every second.

ESP32 Get Epoch Unix Time Serial Monitor

Wrapping Up

This was a quick guide showing you how to get epoch/unix time with the ESP32. 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 ESP32 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 ESP32, 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 »


Enjoyed this project? Stay updated by subscribing our newsletter!

5 thoughts on “Get Epoch/Unix Time with the ESP32 (Arduino)”

  1. Hi, how to change it to milliseconds? I try multiply it by 1000 and it shows wrong time. I do like this, Serial.println(epochTime * 1000);

    Reply
  2. Great site for newbies like me – than you for all the effort.

    I have a question regarding NTP requests: does each call of the function cause network traffic or ist there some „intelligence“ in the system that the internal clock is used for frequent requests and the NTP servers are only called once in a while to synchronise?

    I need the time very frequently but want to avoid permanent network traffic.

    Thanks for consideration,

    Thomas

    Reply
  3. I have tried this code a number of times but in each case I get the “Failed to obtain time” message.
    This code was embedded into the Telegram Bot software which works brilliantly. So the internet access is working OK. Even the stand-alone code fails to work.
    Any suggestions. ?
    Thanks in advance.

    Reply
    • Hi.
      That’s weird.
      I’ve just testes the code now and it is working fine for me.
      What’s the ESP32 add-on version that you’re using? You can check it by going to Tools > Board > Boards Manager and search for ESP32.
      Regards,
      Sara

      Reply

Leave a Reply to Andrew 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.