How do you get a timestamp in Arduino-ESP8266?

NTP is the proven way of getting time remotely. NTP libraries, like @Marcel denotes, is making UDP connections to a server with an interval. So you do not need to do any polling to the server before using it.

Here is the usage of an NTP library with a one-hour offset and one minute refresh interval:

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

#define NTP_OFFSET   60 * 60      // In seconds
#define NTP_INTERVAL 60 * 1000    // In miliseconds
#define NTP_ADDRESS  "europe.pool.ntp.org"

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);

void setup(){
  timeClient.begin();
}

void loop() {
  timeClient.update();
}

To get a timestamp or formatted time anytime you want, use the functions:

String formattedTime = timeClient.getFormattedTime();
unsigned long epcohTime =  timeClient.getEpochTime();

Looking at that code I don't think this microcontroller directly has a clock built in as mentioned. Since you have Wi-Fi though you could make a web query to get it instead.

I'd use a REST query to a place like this:

https://timezonedb.com/api

Which will give you back a JSON formatted time. If you only need accuracy +/- a few seconds that will be fine. You could lower the bandwidth / improve battery life by setting the time like this and then using an internal timer to calculate an offset instead of making a query every time you need a time stamp. Eventually you would need to requery the time and 'correct' it since your timer on that probably is not accurate for long periods of time, plus it could eventually roll over.

If you need the time more accurately then that you will likely need a clock. You could try to do a bit of correction based on ping, but all in all how accurate it needs to be is based on your project requirements.


Contact a specific date/time API on the Internet as described by user2927848. Or send a simple HTTP request to a server you trust and read the Date response header.

If you need greater precision, you may want to use an NTP client for Arduino.