How to Set the Current Datetime with NodeMCU

By May 31, 2016IoT

ClockWhen the ESP8266 starts up, the Realtime Clock (RTC) is not initialized. If your IoT project has the need to provide timestamps in its generated data, then your code will need to fetch the current datetime from a server after the network is available.

One way to do this with NodeMCU is to use the sntp (Simple Network Time Protocol) module in conjunction with the rtctime module. The sntp module will fetch the time from a specified time server (could be on your LAN, or from an official source on the internet) and then set the RTC’s clock to the results of the query. Then you can get the current datetime (as a Unix timestamp data type) whenever needed from the rtctime module:

Another approach of retrieving the current datetime is not exactly built into the current firmware, but can be easily added. This involves making an HTTP request to a webserver that returns a Date header in the response, and parsing that date text in order to obtain the current datetime. While SNTP tries to resolve network latency to within milliseconds, this approach has no built-in compensation, so it may not be useful to you if all of your devices need to be exactly in sync for some reason. However, it is fast and does not require the sntp module to work – this may be beneficial if you are trying to reduce the modules used in your firmware build, or if outbound port 123 is blocked by the router/firewall.

In your Lua script, start by making a HEAD request to a webserver of your choosing (such as www.google.com). This can be done using the net module and parsing the results:

Retrieve the Date header and parse it. Then set the current time manually:

The rtctime.mktime() function is not part of the official firmware at this time. But, it’s an easy function to add to the rtctime.c source code, and is a merely a wrapper around the SDK’s system_mktime() function:

 

The following two tabs change content below.
  • You might want to check in rtctime_mktime that the input is not beyond 2038/01/19 03:14:07 UTC (epoch 2^31-1).

    Oh, sorry…didn’t realize you’re using a 64 bit epoch.