I'm writing a sketch in order to upload to a Sonoff device ( Remote relay, based ESP8266 ).

All is working great, but I wish my MQTT pubs to contain following format:

[ DATE & TIME ] msg

ESP8266 is connected to the internet. I;m looking for a way doing it (including periodic time updates ) without running all 1MB memory, meaning: a code that 1) get time from external source (LAN or WAN ) 2) update it every 24h 3) Lite code ?


  • please ask a specific question
    – jsotola
    Aug 11, 2018 at 18:33
  • updated, tough it seemed straight foreward
    – guyd
    Aug 11, 2018 at 18:38
  • look into NTC, i think there's a built-in example, if not it's a very common lib with examples once added in the manager.
    – dandavis
    Aug 11, 2018 at 19:08
  • @dandavis You mean NTP surely...
    – Majenko
    Aug 11, 2018 at 19:42
  • @Majenko: good eye, that's what i meant, NTP. network time prototcol.
    – dandavis
    Aug 11, 2018 at 19:46

1 Answer 1


Start with the ESP8266WiFi "NTPClient" example. That will teach you how you can get the "Unix Epoch" time from the internet.

That value can be fed directly into TimeLib to keep track of the time for you (indeed, TimeLib includes an NTP example for Arduino Ethernet that should help you get started). Do that periodically (daily, hourly, whatever), and you have your time. TimeLib can then give you the date and time as individual components (hours, minutes, etc), which you can then construct together (I'd use snprintf) to include in your MQTT message:

int len = strlen(message) + 25;
char mqttMessage[len];
snprintf(mqttMessage, len, "[%04d/%02d/%02d %02d:%02d:%02d] %s",
    year(), month(), day(), hour(), minute(), second(), message);

mqttMessage => "[2018/08/11 20:36:24] foo"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.