timestampesp8266ntparduino-esp8266

How do you get a timestamp in Arduino-ESP8266?


I would like to get a timestamp with Arduino-ESP8266.

But I don't have any idea how to get that.

I suppose we have to get the time from the Internet since the ESP8266 doesn't have any clock. Do we need to do that only once or every time we need a timestamp?

I'm already connected by Wi-Fi to the Internet.


Solution

  • 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();