Using TimezoneDB with Electric Imp

Something that can be useful to know when doing some kind of logging, error reporting, or what else it could be, is when it happened. The big problem with time is that it is not the same all over the world, it is not even an absolute offset since some regions got day time saving where the time is offset another hour. To make it even more difficult it is done at different times too… You could either take account for all that yourself, or have someone else do it for you… I am lazy, so I like have others doing things for me, so this is what I do.

Over at you can create a free account, and then they will tell you what time it is at the location you would like to know more about. What we want is their API, which will return a timestamp with the unix time, and the offset to that, depending on the region you asked about.

In this example I want to use the time in Denmark, which is in Europe, and got Copenhagen as capital city, so I put in “Europe/Copenhagen”. If you are not sure what you should put in, or if you get an error, you can see the supported list here

TIMEZONEDB_KEY <- "xxxxxxxxxx";
TIMEZONEDB_ZONE <- "Europe/Copenhagen";
function timeZoneDB()
  local url = "" + TIMEZONEDB_ZONE + "&format=json&key=" + TIMEZONEDB_KEY;
    if (resp.statuscode == 200)
      local data = http.jsondecode(resp.body);
      if ("status" in data)
        if (data.status == "OK")
          TIMEZONE_OFFSET = data.gmtOffset.tointeger();
          server.log("TimeZoneDB > Time offset: " + TIMEZONE_OFFSET + " seconds.")
          server.log("TimeZoneDB returned: " + resp.body);

This code will contact the timezonedb api, and set TIMEZONE_OFFSET to the offset from the timestamp/unix time.

After having used this function, you can as an example use this code to show the time for the zone you asked timezonedb about.

local t = date(time() + TIMEZONE_OFFSET, 'l');
server.log(format("%02d:%02d:%02d", t.hour, t.min, t.sec));

This will hopefully make things a lot easier for you.

Leave a Comment